1.String常用方法:
length():获取当前字符串长度(个数)
public class LengthDemo {
public static void main(String[] args) {
String str = "我爱Java!";
int len = str.length(); //获取str的长度
System.out.println(len); //7
}
}
trim():去除当前字符串两边的空白字符
public class TrimDemo {
public static void main(String[] args) {
String str = " hello world ";
System.out.println(str); // hello world
str = str.trim(); //去除str两边的空白字符,并将去除之后的新的对象存储到str中
System.out.println(str); //hello world
toUpperCase()/toLowerCase():将当前字符串中的英文部分转换为全大写/小写
public class ToUpperCaseDemo {
public static void main(String[] args) {
String str = "我爱Java!";
String upper = str.toUpperCase(); //将str中的英文部分转换为全大写,并存入upper中
System.out.println(upper); //我爱JAVA!
String lower = str.toLowerCase(); //将str中的英文部分转换为全小写,并存入lower中
System.out.println(lower); //我爱java!
startsWith()/endsWith() : 判断当前字符串是否是以给定的字符串开始/结束的
public class StartsWithDemo {
public static void main(String[] args) {
String str = "thinking in java"; //java编程思想(java经典书---工具书)
boolean starts = str.startsWith("think"); //判断str是否是以think开头的
System.out.println(starts); //true
boolean ends = str.endsWith(".png"); //判断str是否是以.png结尾的
System.out.println(ends); //false
charAt():返回当前字符串指定位置上的字符-----根据位置下标找字符
public class CharAtDemo {
public static void main(String[] args) {
// 111111-------和下面的连成10/11/12/13/14/15
// 0123456789012345
String str = "thinking in java";
char c = str.charAt(9); //获取str中下标9所对应的字符
System.out.println(c); //i
indexOf()/lastIndexOf:检索给定字符串在当前字符串中第一次/最后一次出现的位置----根据字符找位置
public class IndexOfDemo {
public static void main(String[] args) {
// 111111
// 0123456789012345
String str = "thinking in java";
int index = str.indexOf("in"); //检索in在str中第1次出现的位置
System.out.println(index); //2
index = str.indexOf("in",3); //从下标为3的位置开始找in第1次出现的位置
System.out.println(index); //5
index = str.indexOf("abc"); //若字符串在str中不存在,则返回-1
System.out.println(index); //-1
index = str.lastIndexOf("in"); //检索in在str中最后一次出现的位置
System.out.println(index); //9
substring():截取当前字符串中的指定范围的字符串(含头不含尾)
public class SubstringDemo {
public static void main(String[] args) {
// 1
// 01234567890
String str = "www.tttt.cn";
int start = str.indexOf(".")+1; //4
int end = str.lastIndexOf("."); //8
String name = str.substring(start,end); //截取下标4到7的字符串
System.out.println(name); //tttt
name = str.substring(4); //从下标4一直截到最后
System.out.println(name); //tttt.cn
// 1111111
// 01234567890123456
str = "www.anerat.com.cn";
start = str.indexOf(".")+1; //4
end = str.indexOf(".",start); //10
name = str.substring(start,end);
System.out.println(name);
静态方法valueOf():将其他数据类型转换为字符串String