String9个常用方法

1.indexOf(String str) 方法功能:获取str在整个字符串中第一次出现的索引位置
str:入参字符串,含义为被查找的子字符串
返回类型:int
结果含义:第一次出现的位置,如果没有出现过,返回-1
案例:在 "我爱你中国,我爱你世界" String word="我爱你中国,我爱你世界";

int position = word.indexOf("暑期班"); 
System.out.println(position);输出结果-1

2.String trim()方法功能:去除字符串两端的空格,中间的空格不变

案例:

String word2=" 我 爱 ";
String trim = word2.trim();
String result=trim.replaceAll(" ","");
System.out.println(result);

3.equalsIgnoreCase()方法功能:忽略大小写进行对比

案例:

public static void main(String[] args) {
String word="ABC你好dEF";
String newWord = word.toLowerCase();
System.out.println(newWord);
}

 4.concat()方法功能:字符串拼接
案例:

public static void main(String[] args) {
String wordA="暑期班";

String wordB="无敌班";
String allWord = wordA.concat(wordB);
System.out.println(allWord);
}

5.args()方法功能:字符串拆分

案例:

public static void main(String[] args) {
String song="1@一块板儿搭两旁,一头低来一头高。小朋友们都爱它,一上一下真好玩。(打一娱乐设施)@跷跷板";
String[] words = song.split("@");
for (String item : words) {
System.out.println(item);
}

6.substring(int index)方法功能:提取从位置索引开始的字符串部分

案例:

String word="我爱你中国,我爱你世界";
String result1 = word.substring(1,3);
System.out.println(result1);

7.count()方法功能:查找字符出现次数

案例:

public static void main(String[] args) {
String str="我爱你中国,我爱你故乡";
String findStr="国";
String[] word=new String[str.length()];
for(int i = 0;i< word.length;i++) {
word[i]=str.substring(i,i+1);
}
int count=0;
for(String item : word) {
if(item.equals(findStr)) {
count++;
}
}
System.out.println(count);
}

8.lastIndexOf()方法功能:查找值位置

案例:

String word1="我爱你中国,我爱你世界";

int lastIndex = word1.lastIndexOf("爱你");
System.out.println(lastIndex);

9.length()方法功能:统计字符串字符总个数

 案例:

public static void main(String[] args){

String name="今天是个好天气";

int length = name.length();

System.out.println(length);

}

猜你喜欢

转载自www.cnblogs.com/Rokem/p/11306130.html