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编程思想(经典书)
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
//从下标为3的位置开始找in第1次出现的位置
index = str.indexOf("in",3);
System.out.println(index); //5
index = str.indexOf("abc"); //若字符串在str中不存在,则返回-1
System.out.println(index); //-1
index = str.lastIndexOf("in"); //找in最后一次出现的位置
System.out.println(index); //9
}
}
- substring():截取当前字符串中指定范围内的字符串(含头不含尾–包含start,但不包含end)
public class SubstringDemo {
public static void main(String[] args) {
// 1
// 01234567890
String str = "www.tedu.cn";
String name = str.substring(4,8);
System.out.println(name); //tedu
name = str.substring(4); //从下标4开始一直到末尾
System.out.println(name); //tedu.cn
}
}
- 静态方法valueOf():将其它数据类型转换为String
public class ValueOfDemo {
public static void main(String[] args) {
int a = 123;
String s1 = String.valueOf(a); //将int型变量a转换为String类型并赋值给s1
System.out.println(s1); //123---字符串类型
double b = 123.456;
String s2 = String.valueOf(b); //将double型变量b转换为String类型并赋值给s2
System.out.println(s2); //123.456---字符串类型
String s3 = b+""; //任何类型与字符串相连,结果都变为字符串类型,效率低(一会讲)
System.out.println(s3); //123.456---字符串类型
}
}
Original: https://www.cnblogs.com/Bafanqwq/p/16571372.html
Author: 八幡qwq
Title: api接口基础Day1
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/683634/
转载文章受原作者版权保护。转载请注明原作者出处!