package com.dl7.mvp.utils;
import android.text.TextUtils;
import com.orhanobut.logger.Logger;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by long on 2016/8/29.
* 字符串工具
*/
public class StringUtils {
private StringUtils() {
throw new RuntimeException("StringUtils cannot be initialized!");
}
/**
* 计算图片要显示的高度
*
* @param pixel 原始分辨率
* @param width 要显示的宽度
* @return
*/
public static int calcPhotoHeight(String pixel, int width) {
int height = -1;
int index = pixel.indexOf("*");
if (index != -1) {
try {
int widthPixel = Integer.parseInt(pixel.substring(0, index));
int heightPixel = Integer.parseInt(pixel.substring(index + 1));
height = (int) (heightPixel * (width * 1.0f / widthPixel));
} catch (NumberFormatException e) {
Logger.e(e.toString());
return -1;
}
}
return height;
}
/**
* 裁剪新闻的 Source 数据
*
* @param source
* @return
*/
public static String clipNewsSource(String source) {
if (TextUtils.isEmpty(source)) {
return source;
}
int i = source.indexOf("-");
if (i != -1) {
return source.substring(0, i);
}
return source;
}
/**
* 裁剪图集ID
*
* @param photoId
* @return
*/
public static String clipPhotoSetId(String photoId) {
if (TextUtils.isEmpty(photoId)) {
return photoId;
}
int i = photoId.indexOf("|");
if (i >= 4) {
String result = photoId.replace('|', '/');
return result.substring(i - 4);
}
return null;
}
/**
* 转换文件路径
*
* @param filePath 原路径
* @return
*/
public static String replaceFilePath(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return filePath;
}
if (filePath.startsWith("/sdcard") && SDCardUtils.getRootPath() != null) {
filePath = filePath.replaceFirst("/sdcard", SDCardUtils.getRootPath());
filePath = filePath.replace(":", File.separator);
}
return filePath;
}
/**
* is null or its length is 0 or it is made by space
* <p/>
* <pre>
* isBlank(null) = true;
* isBlank("") = true;
* isBlank(" ") = true;
* isBlank("a") = false;
* isBlank("a ") = false;
* isBlank(" a") = false;
* isBlank("a b") = false;
* </pre>
*
* @param str
* @return if string is null or its size is 0 or it is made by space, return true, else return false.
*/
public static boolean isBlank(String str) {
return (str == null || str.trim().length() == 0);
}
/**
* is null or its length is 0
* <p/>
* <pre>
* isEmpty(null) = true;
* isEmpty("") = true;
* isEmpty(" ") = false;
* </pre>
*
* @param str
* @return if string is null or its size is 0, return true, else return false.
*/
public static boolean isEmpty(CharSequence str) {
return (str == null || str.length() == 0);
}
/**
* 判断给定的字符串是否不为null且不为空
*
* @param string 给定的字符串
*/
public static boolean isNotEmpty(String string) {
return !isEmpty(string);
}
/**
* get length of CharSequence
* <p/>
* <pre>
* length(null) = 0;
* length(\"\") = 0;
* length(\"abc\") = 3;
* </pre>
*
* @param str
* @return if str is null or empty, return 0, else return {@link CharSequence#length()}.
*/
public static int length(CharSequence str) {
return str == null ? 0 : str.length();
}
/**
* null Object to empty string
* <p/>
* <pre>
* nullStrToEmpty(null) = "";
* nullStrToEmpty("") = "";
* nullStrToEmpty("aa") = "aa";
* </pre>
*
* @param str
* @return
*/
public static String nullStrToEmpty(Object str) {
return (str == null ? "" : (str instanceof String ? (String) str : str.toString()));
}
/**
* capitalize first letter
* <p/>
* <pre>
* capitalizeFirstLetter(null) = null;
* capitalizeFirstLetter("") = "";
* capitalizeFirstLetter("2ab") = "2ab"
* capitalizeFirstLetter("a") = "A"
* capitalizeFirstLetter("ab") = "Ab"
* capitalizeFirstLetter("Abc") = "Abc"
* </pre>
*
* @param str
* @return
*/
public static String capitalizeFirstLetter(String str) {
if (isEmpty(str)) {
return str;
}
char c = str.charAt(0);
return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length())
.append(Character.toUpperCase(c)).append(str.substring(1)).toString();
}
/**
* encoded in utf-8
* <p/>
* <pre>
* utf8Encode(null) = null
* utf8Encode("") = "";
* utf8Encode("aa") = "aa";
* utf8Encode("啊啊啊啊") = "%E5%95%8A%E5%95%8A%E5%95%8A%E5%95%8A";
* </pre>
*
* @param str
* @return
* @throws UnsupportedEncodingException if an error occurs
*/
public static String utf8Encode(String str) {
if (!isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UnsupportedEncodingException occurred. ", e);
}
}
return str;
}
/**
* encoded in utf-8, if exception, return defultReturn
*
* @param str
* @param defultReturn
* @return
*/
public static String utf8Encode(String str, String defultReturn) {
if (!isEmpty(str) && str.getBytes().length != str.length()) {
try {
return URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
return defultReturn;
}
}
return str;
}
/**
* get innerHtml from href
* <p/>
* <pre>
* getHrefInnerHtml(null) = ""
* getHrefInnerHtml("") = ""
* getHrefInnerHtml("mp3") = "mp3";
* getHrefInnerHtml("<a innerHtml</a>") = "<a innerHtml</a>";
* getHrefInnerHtml("<a>innerHtml</a>") = "innerHtml";
* getHrefInnerHtml("<a<a>innerHtml</a>") = "innerHtml";
* getHrefInnerHtml("<a href="baidu.com">innerHtml</a>") = "innerHtml";
* getHrefInnerHtml("<a href="baidu.com" title="baidu">innerHtml</a>") = "innerHtml";
* getHrefInnerHtml(" <a>innerHtml</a> ") = "innerHtml";
* getHrefInnerHtml("<a>innerHtml</a></a>") = "innerHtml";
* getHrefInnerHtml("jack<a>innerHtml</a></a>") = "innerHtml";
* getHrefInnerHtml("<a>innerHtml1</a><a>innerHtml2</a>") = "innerHtml2";
* </pre>
*
* @param href
* @return <ul>
* <li>if href is null, return ""</li>
* <li>if not match regx, return source</li>
* <li>return the last string that match regx</li>
* </ul>
*/
public static String getHrefInnerHtml(String href) {
if (isEmpty(href)) {
return "";
}
String hrefReg = ".*<[\\s]*a[\\s]*.*>(.+?)<[\\s]*/a[\\s]*>.*";
Pattern hrefPattern = Pattern.compile(hrefReg, Pattern.CASE_INSENSITIVE);
Matcher hrefMatcher = hrefPattern.matcher(href);
if (hrefMatcher.matches()) {
return hrefMatcher.group(1);
}
return href;
}
/**
* process special char in html
* <p/>
* <pre>
* htmlEscapeCharsToString(null) = null;
* htmlEscapeCharsToString("") = "";
* htmlEscapeCharsToString("mp3") = "mp3";
* htmlEscapeCharsToString("mp3<") = "mp3<";
* htmlEscapeCharsToString("mp3>") = "mp3\>";
* htmlEscapeCharsToString("mp3&mp4") = "mp3&mp4";
* htmlEscapeCharsToString("mp3"mp4") = "mp3\"mp4";
* htmlEscapeCharsToString("mp3<>&"mp4") = "mp3\<\>&\"mp4";
* </pre>
*
* @param source
* @return
*/
public static String htmlEscapeCharsToString(String source) {
return StringUtils.isEmpty(source) ? source : source.replaceAll("<", "<").replaceAll(">", ">")
.replaceAll("&", "&").replaceAll(""", "\"");
}
/**
* transform half width char to full width char
* <p/>
* <pre>
* fullWidthToHalfWidth(null) = null;
* fullWidthToHalfWidth("") = "";
* fullWidthToHalfWidth(new String(new char[] {12288})) = " ";
* fullWidthToHalfWidth("!"#$%&) = "!\"#$%&";
* </pre>
*
* @param s
* @return
*/
public static String fullWidthToHalfWidth(String s) {
if (isEmpty(s)) {
return s;
}
char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == 12288) {
source[i] = ' ';
// } else if (source[i] == 12290) {
// source[i] = '.';
} else if (source[i] >= 65281 && source[i] <= 65374) {
source[i] = (char) (source[i] - 65248);
} else {
source[i] = source[i];
}
}
return new String(source);
}
/**
* transform full width char to half width char
* <p/>
* <pre>
* halfWidthToFullWidth(null) = null;
* halfWidthToFullWidth("") = "";
* halfWidthToFullWidth(" ") = new String(new char[] {12288});
* halfWidthToFullWidth("!\"#$%&) = "!"#$%&";
* </pre>
*
* @param s
* @return
*/
public static String halfWidthToFullWidth(String s) {
if (isEmpty(s)) {
return s;
}
char[] source = s.toCharArray();
for (int i = 0; i < source.length; i++) {
if (source[i] == ' ') {
source[i] = (char) 12288;
// } else if (source[i] == '.') {
// source[i] = (char)12290;
} else if (source[i] >= 33 && source[i] <= 126) {
source[i] = (char) (source[i] + 65248);
} else {
source[i] = source[i];
}
}
return new String(source);
}
/**
* 格式化字符串
*
* @param msg 格式数据
* @param args 参数
* @return 格式化字符串
*/
public static String formatString(final String msg, Object... args) {
return String.format(Locale.ENGLISH, msg, args);
}
/**
* 转换安装人数
*
* @param hotCount 安装人数
* @return
*/
public static String convertHotCount(int hotCount) {
int tenThousand = 10000;
int hundredMillion = 10000 * 10000;
if (hotCount >= hundredMillion) {
return String.format(Locale.CHINA, "%.1f亿人在用", (float) hotCount / hundredMillion);
} else if (hotCount >= tenThousand) {
float f = (float) hotCount / tenThousand;
return String.format(Locale.CHINA, f > 100 ? "%.0f万人在用" : "%.1f万人在用", f);
} else {
return String.format(Locale.CHINA, "%d人在用", hotCount);
}
}
public static String convertSpeed(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1f G", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f M" : "%.1f M", f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f K" : "%.1f K", f);
} else
return String.format("%d B", size);
}
public static String convertStorageNoB(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1fGB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? "%.0fMB" : "%.1fMB", f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? "%.0fKB" : "%.1fKB", f);
} else
return String.format("%dB", size);
}
/**
* 从url中截取文件名
* @param url
* @return
*/
public static String clipFileName(String url) {
int index = url.lastIndexOf("/");
if (index != -1) {
return url.substring(index + 1);
}
return null;
}
}