1.字符串反转
public static void main(String[] args) {
String s = "abcdef";
System.out.println("原字符串 :" + s);
// String res = reverseString(s);
String res = reverseString(s, 2, 4); // 按指定角标反转
System.out.println("反转字符串:" + res);
}
//字符串反转
public static String reverseString(String s) {
return reverseString(s, 0, s.length());
}
//按指定角标反转
public static String reverseString(String s, int start, int end) {
//字符串变数组
char[] chs = s.toCharArray();
//反转数组
reverse(chs, start, end);
//将数组变成字符串
return new String(chs);
}
public static void reverse(char[] arr, int x, int y) {
for (int start = x, end = y - 1; start < end; start++, end--) {
swap(arr, start, end);
}
}
public static void swap(char[] arr, int x, int y) {
char temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
2.统计一个字符串在另一个字符串中出现的次数
public static void main(String[] args) {
String str = "abccdefccjgeccgfc";
String key = "cc";
int count = getSubCount_2(str, key);
System.out.println("count=" + count);
}
/**
* 统计一个字符串在另一个字符串中出现的次数
* 1,定义一个计数器
* 2,获取key第一次出现的位置
* 3,从第一次出现的位置后剩余的字符串中继续获取key出现的位置,每获取一次就计数一次
* 4,当获取不到时,计数完成
*/
public static int getSubCount(String str, String key) {
int count = 0;
int index = 0;
while ((index = str.indexOf(key)) != -1) {
// System.out.println(str);
str = str.substring(index + key.length());
count++;
}
return count;
}
public static int getSubCount_2(String str, String key) {
int count = 0;
int index = 0;
while ((index = str.indexOf(key, index)) != -1) {
System.out.println("index=" + index);
index = index + key.length();
count++;
}
return count;
}
3.获取两个字符串中最大的相同子串
public static void main(String[] args) {
String s1 = "abchelloworld";
String s2 = "cchellowwow";
String maxSubString = getMaxSubString(s1, s2);
System.out.println(maxSubString);
}
//获取两个字符串中最大的相同子串
public static String getMaxSubString(String s1, String s2) {
String max = "";
String min = "";
max = (s1.length() > s2.length()) ? s1 : s2;
min = (max == s1) ? s2 : s1;
for (int x = 0; x < min.length(); x++) {
for (int y = 0, z = min.length() - x; z != min.length() + 1; y++, z++) {
String temp = min.substring(y, z);
if (max.contains(temp)) {
return temp;
}
}
}
return "";
}