String类常用方法使用 一
String类常用方法使用 二
String类常用方法使用 三
2.5提取部分字符串的方法
2.5.1:获取指定索引位置的字符
使用charAt()方法可以指定索引处的字符返回。
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello Word");
char s = s1.charAt(4);
System.out.println(s);
}
}
运行结果:
o
2.5.2:获取字符串
通过字符串的下标进行截取,且下标是从0开始的。
- substring(int beginIndex):返回的是从指定索引位置开始截取直到该字符串结尾的子串。
- substring(int beginIndex,int endIndex):返回的是从字符串某一索引位置开始截取至某一个索引位置的子串。
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello Word");
System.out.println(s1.substring(2));
System.out.println(s1.substring(2,7));
}
}
第一个输出截取的是 从下标为2的字符到原字符串是s1的结尾
第二个输出截取的是 s1中下标从2到7的字符串
运行结果:
llo Word
llo W
2.5.3:连接连个字符串
concat()方法
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello Word");
s1 = s1.concat("happy!");
System.out.println(s1);
}
}
运行结果:
hello Wordhappy!
2.5.4:字符串的替换
replace():该方法可以实现将指定的字符或者字符串替换成新的字符或者字符串。
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello Word");
s1=s1.replace("hello", "hi");
System.out.println(s1);
}
}
运行结果:
hi Word
2.5.5:去除空格
trim():该方法返回的是字符串的副本,忽略前导的空格和尾部的空格。
package com.dong.test;
public class StringTest {
public static void main(String[] args) {
String s1 = new String("hello Word ");
s1=s1.trim();
System.out.println(s1);
System.out.println(s1.length());
}
}
运行结果:
hello Word
10