-------
android培训、
java培训、期待与您交流! ----------
/*
1.模拟一个trim方法,去除字符串两端的空格。
2.将一个字符串进行反转,将字符串中指定部分进行反转,“abcdefg”
3.获取一个字符串在另个一个字符串中出现的次数。
4.获取两个字符串中最大相同的字串,第一个动作:将短的那个串进行长度
依次递减的字串打印。
*/
代码(一)
class LianXiDemo
{
public static void main(String[] args)
{
String s = " ab cd ";
//String s = "abcde";
sop("("+s+")");
//s = mytrim(s);
s = reverseString(s);
//s = reverseString(s,4,6);
sop("("+s+")");
}
public static void sop(String str)
{
System.out.println(str);
}
/*练习一,去除字符串两端的空格
思路:
1.判断字符串第一个位置是否是空格,如果是继续向下判断,
直到不是空格为止,结尾处判断空格也是如此。
2.当开始和结尾都判断到不是空格时,就是要获取的字符串。
*/
public static String mytrim(String str)
{
int start = 0;
int end = str.length()-1;
while (start<=end && str.charAt(start)==' ')
{
start++ ;
}
while (start<=end && str.charAt(end)==' ')
{
end-- ;
}
return str.substring(start,end+1);
}
/*
练习2.将一个字符串进行反转,将字符串中指定部分进行反转,“abcdefg”
思路:
1,将字符串变成数组。
2. 对数组进行反转。
3. 将数组变成字符串。
*/
public static String reverseString(String str)
{
return reverseString(str,0,str.length());
}
public static String reverseString(String str ,int start,int end)
{
//将字符串转换成数组
char[] arr = str.toCharArray();
//反转数组
reverse(arr,start,end);
//将数组转换成字符串,运用了构造函数方式。
return new String(arr);
}
public static void reverse(char[] arr,int x,int y)
{
int start = x;
int end = y-1;
while (start < end)
{
swap(arr,start,end);
start++;
end--;
}
}
public static void swap(char[] arr,int a,int b)
{
char temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
代码二:
/*
3.获取一个字符串在另个一个字符串中出现的次数。
“abkkcdkkefkkskk”
思路:
1.定义一个计数器
2.获取kk第一次出现的位置
3.从第一次出现位置后剩余的字符串中继续获取kk出现的位置。
没获取一次计数一次
4.当获取不到时,计数完成。
*/
class LianXiDemo2
{
public static void main(String[] args)
{
String str = "abkkcdkkefkkskk";
sop("count="+getSubCount(str,"kk"));
sop("count="+getSubCount_2(str,"kk"));
}
public static int getSubCount(String str,String key)
{
int count = 0;
int index = 0;
while((index = str.indexOf(key))!=-1)
{
sop("str="+str);
str = str.substring(index+key.length());
count++;
}
return count;
}
public static void sop(String str)
{
System.out.println(str);
}
public static int getSubCount_2(String str,String key)
{
int count = 0;
int index = 0;
while((index=str.indexOf(key,index))!=-1)
{
sop("index="+index);
index = index + key.length();
count++;
}
return count;
}
}
代码三:
思路:1,将短的那个字串按照长度递减的方式获取到。
2. 将每获取到的字串去长串中判断是否包含,如果包含,已经找到。
class LianXiDemo3
{
public static void main(String[] args)
{
String s1 = "abcwerthelloyuiodef";
String s2 = "cvhellobnm";
sop(getMaxString(s1,s2));
}
public static void sop(String str)
{
System.out.println(str);
}
public static String getMaxString(String s1,String s2)
{
String max =" ",min = " ";
max = (s1.length()>s2.length())?s1:s2;
min = (max==s1)?s2:s1;
sop("max="+max+"....min="+min);
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);
//sop(temp);
if (max.contains(temp)) //字符串中是否包含temp字符串
return temp;
}
}
return " ";
}
}