016.2 String

时间:2023-03-09 22:10:36
016.2 String

内容:String方法+练习

#######################################
比较方法:equals()
字符串长度:int length()
字符的位置:int indexOf(ch,fromIndex);
获取指定位置上的字符:char charAt(int)
获取部分字符串:String substring(int start,int end);
字符串变成数组:toCharArray()

String方法查找练习:
         * 1,字符串是否以指定字符串开头。结尾同理。
         *         boolean startsWith(string)
         *         boolean endsWith(string)
         *
         * 2,字符串中是否包含另一个字符串。
         *         boolean contains(string);
         *         int indexOf(string)//如果返回-1,表示不存在。
         *
         * 3,字符串中另一个字符串出现的位置。
         *         int indexOf(string)
         * 4,将字符串中指定的字符串替换成另一个字符串。
         *         String replace(oldstring , newstring)
         *
         * 5,字符串如何比较大小?
         *
         * 6,将字符串转成一个字符数组。或者字节数组。
         *         toCharArray()
         *         getBytes()
         * 7,将字母字符串转成大写的字母字符串。
         *         toUpperCase()
         *         toLowerCase();
         * 8,将字符串按照指定的方式分解成多个字符串, "lisi,wangwu,zhaoliu"获取三个姓名。
         *         String[] split(string);

#compareTo(对象)  对象比较方法

############查找一个字符串里面有多少个另外一个字符串

 public class StringTest2_2 {
public static void main(String[] args) {
/*
* 案例二:
* "witcasteritcasttyuiitcastodfghjitcast"有几个itcast
*
* 思路:
* 1,无非就是在一个字符串中查找另一个字符串。indexOf。
* 2,查找到第一次出现的指定字符串后,如何查找第二个呢?
* 3,无需在从头开始,只要从第一次出现的位置+要找的字符串的长度的位置开始向后查找下一个第一次出现的位置即可。
* 4,当返回的位置是-1时,查找结束。
*/
String str = "witcasteritcasttyuiitcastodfghjitcast";
String key = "itcast"; int count = getKeyCount(str,key);
System.out.println("count="+count);
/*
int x = str.indexOf(key,0);//从头开始找。
System.out.println("x="+x); int y = str.indexOf(key,x+key.length());//从指定起始位开始找。
System.out.println("y="+y); int z = str.indexOf(key,y+key.length());//从指定起始位开始找。
System.out.println("z="+z); int a = str.indexOf(key,z+key.length());//从指定起始位开始找。
System.out.println("a="+a); int b = str.indexOf(key,a+key.length());//从指定起始位开始找。
System.out.println("b="+b);
*/
} /**
* 获取key在str中出现次数。
*/
public static int getKeyCount(String str, String key) { //1,定义变量。记录每一次找到的key的位置。
int index = 0;
//2,定义变量,记录出现的次数。
int count = 0; //3,定义循环。只要索引到的位置不是-1,继续查找。
while((index = str.indexOf(key,index))!=-1){ //每循环一次,就要明确下一次查找的起始位置。
index = index + key.length(); //每查找一次,count自增。
count++;
}
return count;
} }

##################另外一个程序:要求,将该字符串按照长度由长到短打印出来

public class StringTest2_3 {
public static void main(String[] args) {
/*
* 案例三: "itcast_sh"要求,将该字符串按照长度由长到短打印出来。 itcast_sh itcast_s tcast_sh
*/
String str = "itcast";
printStringByLength(str);
}
public static void printStringByLength(String str) {
// 1,通过分析,发现是for嵌套循环。
for (int i = 0; i < str.length(); i++) {
for (int start = 0, end = str.length() - i; end <= str.length(); start++, end++) {
//根据start,end截取字符串。
String temp = str.substring(start, end);
System.out.println(temp);
}
}
}
}