android开发字符串工具类(一)
package com.gzcivil.utils; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* 字符串工具
*
* @author LiJinlun
* @time 2015-12-5
*/
public class StringUtils { private static StringUtils instance; private StringUtils() {
super();
} public static String getDateTimeToString(Calendar cal, String format) {
return getDateTimeToString(cal.getTimeInMillis(), format);
} public static String getDateTimeToString(long longTime, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
Date date = new Date(longTime);
return sdf.format(date);
} public static synchronized StringUtils getInstance() {
if (instance == null)
instance = new StringUtils();
return instance;
} /** 将一个字符串从第一位开始截取到有数字出现的地方 */
public static String clearNumberString(String str) {
int minIndex = Integer.MAX_VALUE;
int[] index = new int[10];
for (int i = 0; i < 10; i++) {
index[i] = str.indexOf(String.valueOf(i));
if (index[i] != -1 && index[i] < minIndex) {
minIndex = index[i];
}
}
if (minIndex < Integer.MAX_VALUE) {
str = str.substring(0, minIndex);
}
return str;
} /**
* 判断字符串是否为空
*/
public static boolean isEmpty(String str) {
return null == str || str.trim().equals("");
} /**
* 描述:手机号格式验证.
*
* @param str
* 指定的手机号码字符串
* @return 是否为手机号码格式:是为true,否则false
*/
public static Boolean isMobilePhone(String str) {
Boolean isMobileNo = false;
try {
Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$");
Matcher m = p.matcher(str);
isMobileNo = m.matches();
} catch (Exception e) {
e.printStackTrace();
}
return isMobileNo;
} /**
* 获取字串字节长度
*
* @param str
* @return
*/
public static int getLength(String str) {
return str.replaceAll("[^\\x00-\\xff]", "**").trim().length();
} /** 返回double数据d小数点后面2位有效数字 */
public static double getDouble(double d) {
return new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
} /** 从double型返回String型,精确到小数点后2位 */
public static String getStringByDouble(double d) {
String str = String.valueOf(new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
try {
int index = str.indexOf('.');
if (index != -1) {
String tmpStr = str.substring(index + 1);
if ("0".equals(tmpStr)) {
str = str.substring(0, index);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
} public static String getCorrectDistance(int distance) {
String result = "";
if (distance < 20) {
result = "附近";
} else if (distance < 1000) {
result = distance + "m";
} else {
result = String.format("%.1f", distance / 1000f) + "km";
}
return result;
} /**
* 将秒数转换成文字描述
*
* @param tm单位秒
*/
public static String secondsToString(int tm) {
if (tm <= 0)
return "00:00:00";
long hour = tm / 3600;
tm = tm % 3600;
long min = tm / 60;
tm = tm % 60; String result = "";
if (hour < 10) {
result = "0" + hour + ":";
} else {
result = String.valueOf(hour) + ":";
} if (min < 10) {
result += "0" + min + ":";
} else {
result += min + ":";
} if (tm < 10) {
result += "0" + tm;
} else {
result += String.valueOf(tm);
}
return result;
} /**
* 检测是否JSON字串
*
* @param source
* @return
*/
public static boolean isJson(String source) {
String tmp = null == source ? "" : source.trim();
if ("".equals(tmp) || tmp.length() < 1)
return false;
else if (tmp.startsWith("{") && tmp.endsWith("}"))
return true;
else if (tmp.startsWith("[") && tmp.endsWith("]"))
return true;
else
return false;
} public static String str2int(String source) {
String result = "";
LogUtils.i("ls", "result" + result);
for (int i = 0; i < source.length(); i++) {
if (source.charAt(i) >= '0' && source.charAt(i) <= '9')
result += source.charAt(i); }
return result;
} /**
* MD5编码
*
* @param source
* @return
*/
public static String md5(byte[] source) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
for (int i = 0, k = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
LogUtils.e("md5(): error=" + e.getMessage(), "StringTool");
return "";
}
} /**
* base64编码,将字节数组编码为字符串
*
* @param source
* @return String
*/
public static String base64_encode(byte[] source) {
char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
try {
StringBuffer sb = new StringBuffer();
int len = source.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = source[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = source[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = source[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
} catch (Exception e) {
LogUtils.e("base64_encode(): error=" + e.getMessage(), "StringTool");
return "";
}
} /**
* base64编码,解码为字节数组
*
* @param source
* @return byte[]
*/
public static byte[] base64_decode(String source) {
byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 };
try {
byte[] data = source.getBytes();
int len = data.length;
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
/* b1 */
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1)
break; /* b2 */
do {
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1)
break;
buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */
do {
b3 = data[i++];
if (b3 == 61)
return buf.toByteArray();
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1)
break;
buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */
do {
b4 = data[i++];
if (b4 == 61)
return buf.toByteArray();
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1)
break;
buf.write((int) (((b3 & 0x03) << 6) | b4));
}
return buf.toByteArray();
} catch (Exception e) {
LogUtils.i("ls", "base64_decode(): error=" + e.getMessage());
return "".getBytes();
}
} public static String join(String separator, Object[] o) {
return implode(separator, Arrays.asList(o));
} protected static <T> String implode(String separator, Iterable<T> elements) {
StringBuilder out = new StringBuilder();
boolean first = true;
for (Object s : elements) {
if (s == null)
continue;
else if (first)
first = false;
else
out.append(separator);
out.append(s);
}
return out.toString();
} public static String[] explode(String glue, String str) {
String[] outData;
try {
StringTokenizer st = new StringTokenizer(str, glue);
outData = new String[st.countTokens()];
for (int i = 0; st.hasMoreTokens();) {
outData[i++] = st.nextToken();
}
} catch (Exception e) {
outData = new String[] { str };
e.printStackTrace();
}
return outData;
} /**
* 得到字符串双字节长度
*
* @param str
* @return
*/
public static int getDoubleByteLength(String str) {
return str.replaceAll("[^\\x00-\\xff]", "xx").trim().length();
} /**
* 将流转换成字符串
*
* @param is
* @return
*/
public static String getStringByStream(InputStream is) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
} /**
* 将流转换成字符串
*
* @param is
* @param chatset
* 字符编码
* @return
*/
public static String getStringByStream(InputStream is, String chatset) {
StringBuffer sb = new StringBuffer();
try {
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len, chatset));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return sb.toString();
} }
android开发字符串工具类(一)的更多相关文章
- Android开发常用工具类
来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...
- 最全Android开发常用工具类
主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括 HttpUtils.DownloadManagerPro.Safe.ijiami.ShellUtils.Pack ...
- android 开发 常用工具类
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自[张鸿洋的博客] 打开大家手上的项目,基本都会有一大批的辅 ...
- android开发Tost工具类管理(一)
Tost工具类管理: package com.gzcivil.utils; import android.content.Context; import android.widget.Toast; / ...
- android 开发 在一个工具类(或者适配器class)里启动activity
实现思路: 1.需要给工具类里传入context: 2.使用上下文mContext.startActivity启动activity 例子1: public class SafePlaceRecycle ...
- Android开发 Html工具类详解
前言 在一些需求富文本显示或者编辑的开发情况下,数据都是用html的格式来保存文本信息的.而google是有提供解析html的工具类那就是Html.有了Html可以让TextView也支持富文本(其实 ...
- 网络请求以及网络请求下载图片的工具类 android开发java工具类
package cc.jiusan.www.utils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; ...
- Android 开发小工具之:Tools 属性 (转)
Android 开发小工具之:Tools 属性 http://blog.chengyunfeng.com/?p=755#ixzz4apLZhfmi 今天来介绍一些 Android 开发过程中比较有用但 ...
- Android 开发常用工具合集
在 Android 开发中经常使用到的小功能,用于记录开发的那些事^_^ 1. 获取 release 和 debug 版本的 SHA1 public static String getSHA1(Con ...
随机推荐
- c++引擎开发
MyMap.erase(Itor++); //在windows下也可以Itor = MyMap.erase(Itor),但是在linux下不行. 一个是把指针定为const .就是不能修改指针.也就是 ...
- 跟我一起学extjs5(18--模块的新增、改动、删除操作)
跟我一起学extjs5(18--模块的新增.改动.删除操作) 上节在Grid展示时做了一个金额单位能够手工选择的功能,假设你要增加其它功能.也仅仅要依照这个模式来操作即可了,比方说你想 ...
- android实现透明和半透明效果
从透明到半透明时一个值的变化过程. #00000000(全透明)——#e0000000(半透明) 如果觉得半透明的效果太暗淡.可以设置成#60000000,#80000000,#a0000000等等
- [记录]关于vertical-align单/多选框与说明文字对齐效果
效果图: 第一张使用label标签,第二张没有使用.. 使用label标签,middle对齐方式的单选框下降了1px 而没有使用label标签,sub对齐方式的 却 居 中 了 =_= 不太理解 ...
- canvas模糊事件处理
不知道大家项目中有没有用到canvas时还有时候会出现模糊的情况: 具体推测可能是屏幕改变了,然而canvas的渲染对象并没有跟着一起变: 这里简单介绍个对象,window.devicePixelRa ...
- excel笔记
提取单元格中的数字部分 =MID(LOOKUP(1,-(1&MID(A1,MIN(FIND({0;1;2;3;4;5;6;7;8;9},A1&1/17)),ROW($1:$15)))) ...
- Java File 类的使用方法详解(转)
转自:http://www.codeceo.com/article/java-file-class.html Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对J ...
- java之集合类框架的简要知识点:泛型的类型擦除
这里想说一下在集合框架前需要理解的小知识点,也是个人的肤浅理解,不知道理解的正不正确,请大家多多指教.这里必须谈一下java的泛型,因为它们联系紧密,我们先看一下这几行代码: Class c1 = n ...
- pcl1.7.2_vs2013_x64工程配置
pcl1.7.2_vs2013_x64工程配置 C:\Program Files\PCL 1.7.2\include\pcl-1.7;C:\Program Files\PCL 1.7.2\3rdPar ...
- inux中tail命令---用于查看文件内容
linux中tail命令---用于查看文件内容 最基本的是cat.more和less.1. 如果你只想看文件的前5行,可以使用head命令,如:head -5 /etc/passwd2. 如果你想查看 ...