/*实现 去除字符串两端的空格 charAt(index)_获取下标对应字符
substring(begin,end) 获取子序列
实现 字符串反转 toCharArray 字符串转字符数组
字符串对象初始化方式之一 其构造函数可带数组类型参数
实现 得到A串在B串中出现的次数 b.indexOf(a,bgein) 返回a串在b串(自begin下标开始的)中的首次出现的下标
*/
class StringTest
{
String s;
StringTest(String s)
{
this.s=s;
}
public String myTrim()
{//返回字符串去除两端空格后的部分
int begin=0;
int end=s.length()-1;
//首
while(begin<=end&&s.charAt(begin)==' ')
{//注意!!!begin<=end&&s.charAt(begin)==' '和 s.charAt(begin)==" "&&begin<=end 是有区别的
//这告诉我们,先判断大前提,再判断小前提
begin++;
}
if(begin>end)
return "空格字符串";
//尾
while(begin<=end&&s.charAt(end)==' ')
{
end--;
}
end++;
//返回 begin 到end-1 下标所指示的子序列
return s.substring(begin,end);
}
public String reverseString(String s)
{
//字符串变字符数组
char []ch=s.toCharArray();
//反转数组
reverse(ch);
//数组变回字符串
return new String(ch);
}
public void reverse(char []arr)
{
for(int start=0,end=arr.length-1;start<end;start++,end--)
{
swap(arr,start,end);
}
}
public void swap(char[]arr,int a,int b)
{
arr[a]=(char)(arr[a]^arr[b]);
arr[b]=(char)(arr[a]^arr[b]);
arr[a]=(char)(arr[a]^arr[b]);
}
}
class StringTestDemo
{ public static int getSubCount(String s,String key)
{//输出子串在母串中的数目
int index=0;
int count=0;
while((index=s.indexOf(key,index))!=-1)
{
count++;
//1
// s=s.substring(index+key.length());
//2
index+=key.length();
}
return count;
}
public static void main(String[] args)
{
StringTest st=new StringTest("1234512 ");
String s1=st.myTrim();
System.out.println(s1);
System.out.println(st.reverseString(s1));
System.out.println(getSubCount(s1,"12"));
}
}