您的位置:首页 > 职场人生

黑马程序员------<补>String 综合练习

2013-09-01 16:36 555 查看
1,获取一个子串在字符串中出现的次数。
public static  int getSubCount(String str,String key){

//1,定义变量,一个是计数器,一个是记录位置。
int count = 0;
int index = 0;

//2,调用indexOf方法获取key出现的位置。
while((index = str.indexOf(key,index))!=-1){
index = index + key.length();
count++;
}
return count;
}


2,将给定字符串反转并返回。
public static String reverseString(String str) {
//1,将字符串转成字符数组。
char[] chs = str.toCharArray();
reverseArrary(chs);
return new String(chs);//通过构造器将字符数组转成字符串。
}
/*
* 将一个字符数组进行反转。
*/
private static void reverseArrary(char[] chs) {

for (int start = 0,end = chs.length - 1; start < end; start++,end--) {
swap(chs,start,end);
}

}
/*
* 对字符数组元素进行位置的置换。
*/
private static void swap(char[] chs, int start, int end) {
char temp = chs[start];
chs[start] = chs[end];
chs[end] = temp;
}

3,对一个字符串中的字符进行字典顺序的排序生成一个有序的字符串。

public static String sortString(String str) {
//1,将字符串转成字符数组。
char[] chs = str.toCharArray();

//2,对数组排序。
mySort(chs);
return new String(chs);
}

private static void mySort(char[] chs) {

for(int x=0; x<chs.length-1; x++){
for(int y=x+1; y<chs.length; y++){
if(chs[x]>chs[y]){
swap(chs,x,y);
}
}
}
}
private static void swap(char[] chs, int x, int y) {
char temp = chs[x];
chs[x] = chs[y];
chs[y] = temp;
}

4,获取两个字符串中最大相同子串。

public static String getMaxSubstring(String s1, String s2) {

String max,min;
max = s1.length()>s2.length()?s1:s2;
min = max.equals(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++){
//获取s2子串
String temp = min.substring(y,z);
if(max.contains(temp)){
return temp;
}

}
}

return null;
}
5.

有一个字符串数组{"cba","abc","nba","zz","qq","aaa"}.
对这个字符串数组进行字典顺序的排序。
{"aaa","abc","cba","nba","qq","zz"}

public static void main(String[] args) {

String[] strs = {"cba","abc","nba","zz","qq","aaa"};

sortString(strs);

for (int i = 0; i < strs.length; i++) {
System.out.print(strs[i]+",");
}

}
/**
* 对字符串数组进行排序,按照字典顺序。
* @param strs
*/
public static void sortString(String[] strs) {

for (int i = 0; i < strs.length-1; i++) {
for (int j = i+1; j < strs.length; j++) {

if(strs[i].compareTo(strs[j])>0)
swap(strs,i,j);
}
}

}
/*
* 对字符串数组中的元素进行位置的置换。
*/
private static void swap(String[] strs, int i, int j) {

String  temp = strs[i];
strs[i] = strs[j];
strs[j] = temp;
}
public static void sort(int[] arr){
for (int i = 0; i < arr.length-1; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i]>arr[j]){
swap(arr,i,j);
}
}
}
}

private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: