1,给定一个字符串数组。按照字典顺序进行从小到大的排序。
{"nba","abc","cba","zz","qq","haha"}
/*
* 1,给定一个字符串数组。按照字典顺序进行从小到大的排序。
* {"nba","abc","cba","zz","qq","haha"}
*
* 思路:
* 1,对数组排序。可以用选择,冒泡都行。
* 2,for嵌套和比较以及换位。
* 3,问题:以前排的是整数,比较用的比较运算符,可是现在是字符串对象。
* 字符串对象怎么比较呢?爽了,对象中提供了用于字符串对象比较的功能。
*/
public class StringTest_1 {
/**
* @param args
*/
public static void main(String[] args) {
String[] arr = { "nba", "abc", "cba", "zz", "qq", "haha" };
printArray(arr);
sortString(arr);
printArray(arr);
}
public static void sortString(String[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if(arr[i].compareTo(arr[j])>0)//字符串比较用compareTo方法
swap(arr,i,j);
}
}
}
private static void swap(String[] arr, int i, int j) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void printArray(String[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i != arr.length - 1)
System.out.print(arr[i] + ", ");
else
System.out.println(arr[i] + "]");
}
}
}
2,一个子串在整串中出现的次数。
"nbaernbatynbauinbaopnba"
/*
* 2,一个子串在整串中出现的次数。
* "nbaernbatynbauinbaopnba"
* 思路:
* 1,要找的子串是否存在,如果存在获取其出现的位置。这个可以使用indexOf完成。
* 2,如果找到了,那么就记录出现的位置并在剩余的字符串中继续查找该子串,
* 而剩余字符串的起始位是出现位置+子串的长度.
* 3,以此类推,通过循环完成查找,如果找不到就是-1,并对 每次找到用计数器记录。
*/
public class StringTest_2 {
public static void main(String[] args) {
String str = "nbaernbatnbaynbauinbaopnba";
String key = "nba";
int count = getKeyStringCount_2(str,key);
System.out.println("count="+count);
}
public static int getKeyStringCount_2(String str, String key) {
int count = 0;
int index = 0;
while((index = str.indexOf(key,index))!=-1){
index = index + key.length();
count++;
}
return count;
}
}
3,两个字符串中最大相同的子串。
/*
* 3,两个字符串中最大相同的子串。
* "qwerabcdtyuiop"
* "xcabcdvbn"
*
* 思路:
* 1,既然取得是最大子串,先看短的那个字符串是否在长的那个字符串中。
* 如果存在,短的那个字符串就是最大子串。
* 2,如果不是呢,那么就将短的那个子串进行长度递减的方式去子串,去长串中判断是否存在。
* 如果存在就已找到,就不用在找了。
*/
public class StringTest_3 {
public static void main(String[] args) {
String s1 = "qwerabcdtyuiop";
String s2 = "xcabcdvbn";
String s = getMaxSubstring(s2, s1);
System.out.println("s=" + s);
}
/**
* 获取最大子串
*/
public static String getMaxSubstring(String s1, String s2) {
String max = null,min = null;
max = (s1.length()>s2.length())?s1:s2;
min = max.equals(s1)?s2:s1;
System.out.println("max="+max);
System.out.println("min="+min);
for (int i = 0; i < min.length(); i++) {
for(int a = 0,b = min.length()-i; b != min.length()+1; a++,b++){
String sub = min.substring(a, b);
if(max.contains(sub))
return sub;
}
}
return null;
}
}