Android中字符串操作简介
2017-08-17 本文已影响0人
kjy_112233
字符串排序(冒泡排序)
public static String strSort(String str){
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
for (int j = i + 1; j < chars.length; j++) {
if(chars[i] < chars[j]){
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
return new String(chars);
}
字符串比较大小
public static int strSort(String str1, String str2) {
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
int size = chars1.length < chars2.length ? chars1.length : chars2.length;
for (int i = 0; i < size; i++) {
if (intCompare(chars1[i], chars2[i]) != 0)
return intCompare(chars1[i], chars2[i]);
}
return intCompare(chars1.length, chars2.length);
}
private static int intCompare(char char1, char char2) {
if (char1 > char2) {
return 1;
} else if (char1 < char2) {
return -1;
} else {
return 0;
}
}
private static int intCompare(int char1, int char2) {
if (char1 < char2) {
return -1;
} else if (char1 > char2) {
return 1;
} else {
return 0;
}
}
反转字符串
public static String reverseString(String str) {
if (str == null || str.length() < 2)
return str;
return reverseString(str.substring(1, str.length())) + str.charAt(0);
}
获取某段字符
public static String cutOutString(String str) {
return str.substring(str.indexOf("ah"), str.indexOf("bd"));
}
判断字符串中出现的子字符串的次数
public static int countStr(String str, String key) {
int total = 0;
for (String tmp = str; tmp != null && tmp.length() >= key.length(); ) {
if (tmp.indexOf(key) == 0)
total++;
tmp = tmp.substring(1);
}
return total;
}