String类的常用方法及基本使用
1.charAt(int index):返回指定索引处的char值
package m10d27;
public class String_3 {
public static void main(String[] args) {
String str="abcdefg";
char ch=str.charAt(3);
System.out.println(ch);
for(int i=0;i<str.length();i++){
System.out.print(str.charAt(i)+" ");
}
}
}
输出结果:
d
a b c d e f g
2.indexOf(int ch):返回指定字符在此字符串中第一次出现的索引;
package m10d27;
public class String_3 {
public static void main(String[] args) {
String str="abcdedcba";
//返回指定字符在此字符串中第一次出现的索引
int ch=str.indexOf('c');
//返回在此字符串中第一次出现指定字符处的索引,从指定的索引(也就是3)开始搜索。
int ch1=str.indexOf('c',3);
System.out.println(ch);
System.out.println(ch1);
}
}
输出结果为:
2
6
3.substring(int beginIndex):
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
package m10d27;
public class String_3 {
public static void main(String[] args) {
String str="abcdedcba";
/**
* substring(int beginIndex);
* 返回一个新的字符串,它是此字符串的一个子字符串。
* 该子字符串从指定索引处的字符开始,直到此字符串末尾。
*/
String ch=str.substring(3);
/**
* String substring(int beginIndex,int endIndex)
* 返回一个新字符串,它是此字符串的一个子字符串。
* 该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。
* 因此,该子字符串的长度为 endIndex-beginIndex。
*/
String ch1=str.substring(3, 7);//注意是不包括索引为7的这个字符
System.out.println(ch);
System.out.println(ch1);
}
}
输出结果为:
dedcba
dedc
4.toUpperCase()和toLowerCase()方法:将字符串中所有字符转化为大写或者小写;
package m10d27;
public class String_3 {
public static void main(String[] args) {
String str="abcdedcba";
//将此 str中的所有字符都转换为大写
String str1=str.toUpperCase();
System.out.println(str1);
//将此 str1中的所有字符都转换为大写
String str2=str1.toLowerCase();
System.out.println(str2);
}
}
输出结果为:
ABCDEDCBA
abcdedcba
5.trim()方法:去掉字符串前后空格;
package m10d27;
public class String_3 {
public static void main(String[] args) {
String str=" abcdedcba ";
System.out.println(str);
//去掉前后空格后的字符串
String str1=str.trim();
System.out.println(str1);
}
}
输出结果为:
abcdedcba
abcdedcba
可以明显看到前后空格已经去掉;