·indexOf()
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置
如果没有找到匹配的字符串则返回 -1
① 语法:indexOf(String str);
参数:str:要查找的字符串
String test ="I like Chinese food";
System.out.println(test.indexOf("Chinese"));//7
输出结果:7
下标是从0开始的,要查找该字符串中Chinese首次出现的位置,输出下标是7
注意indexOf()方法是区分字母大小写的!!!
② 语法:indexOf(String str, int fromIndex);
参数:str:要查找的字符串
fromIndex:开始查找的起始位置(下标)
String test ="I like Chinese food";
System.out.println(test.indexOf("e",8));//11
输出结果:11
下标是从8开始查找的,而test[8]是"h","h"往后查找"e"的位置,输出的下标是11
·charAt()
charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1
语法:public char charAt(int index)
参数:index:字符的索引
String test ="I like Chinese food";
System.out.println(test.charAt(8));//h
输出结果:h
·length()
① length方法用于获取String字符串中字符的个数
String test ="food";
System.out.println(test.length());//4
输出结果:4
因为代码中字符串有四个字符组成,故此输出结果是4
② 还有一种是用于获取数组的长度
int [] arr = new int[5];
System.out.println(arr.length);//5
输出结果:5
·equals()
equals() 方法用于判断 Number 对象与方法的参数进是否相等
语法:public boolean equals(Object o)
参数:o:任何对象
String a="a";
String b="a";
char c ='a';
System.out.println(a.equals(b));//true
System.out.println(a.equals(c));//false
输出结果:true false
注意:只有对象在不为null且方法的参数类型与数值都相等返回 True,否则返回 False
·trim()
trim() 方法用于删除字符串的头尾空白符
String a =" 我 和我的 祖国 ";
System.out.println(a.trim());//我 和我的 祖国
输出结果:我 和我的 祖国
注意:trim()方法只能清除字符串开头和结尾的空白符号 !!!
·toLowerCase()
toLowerCase() 方法用于将大写字符转换为小写
① 语法:char toLowerCase()
String a ="I Love eat Healthy food";
System.out.println(a.toLowerCase());//i love eat healthy food
输出结果:i love eat healthy food
② 语法:char toLowerCase(char ch)
参数:ch -- 要转换的字符
System.out.println(Character.toLowerCase('a'));//a
System.out.println(Character.toLowerCase('A'));//a
输出结果:a a
·toUpperCase()
toUpperCase() 方法将字符串小写字符转换为大写
① 语法:public String toUpperCase()
String a ="I Love eat Healthy food";
System.out.println(a.toUpperCase());//I LOVE EAT HEALTHY FOOD
输出结果:I LOVE EAT HEALTHY FOOD
② 语法:public String toUpperCase(Locale locale)
System.out.println(Character.toUpperCase('a'));//A
System.out.println(Character.toUpperCase('A'));//A
输出结果:A A