Java中的字符串是一个非常常用的数据类型,它提供了许多内置的方法来操作字符串。以下是一些常用的Java字符串方法:
length(): 返回字符串的长度。
String str = "Hello, World!";
int len = str.length(); // len will be 13
charAt(int index): 返回指定索引处的字符。
char ch = str.charAt(0); // ch will be 'H'
substring(int beginIndex, int endIndex): 返回一个新的字符串,它是此字符串的一个子字符串。
String sub = str.substring(0, 5); // sub will be "Hello"
substring(int beginIndex): 返回一个新的字符串,它是此字符串的一个子字符串。
String sub = str.substring(7); // sub will be "World!"
indexOf(String s): 返回指定子字符串在此字符串中第一次出现的索引。
int index = str.indexOf("World"); // index will be 7
lastIndexOf(String s): 返回指定子字符串在此字符串中最后一次出现的索引。
int index = str.lastIndexOf("l"); // index will be 10
contains(CharSequence s): 判断字符串是否包含指定的字符序列。
boolean contains = str.contains("World"); // contains will be true
startsWith(String prefix): 判断字符串是否以指定的前缀开始。
boolean startsWith = str.startsWith("Hello"); // startsWith will be true
endsWith(String suffix): 判断字符串是否以指定的后缀结束。
boolean endsWith = str.endsWith("World!"); // endsWith will be true
equals(Object anObject): 将此字符串与指定的对象进行比较。
boolean isEqual = str.equals("Hello, World!"); // isEqual will be true
equalsIgnoreCase(String anotherString): 将此字符串与另一个字符串进行比较,忽略大小写。
boolean isEqualIgnoreCase = str.equalsIgnoreCase("hello, world!"); // isEqualIgnoreCase will be true
trim(): 返回字符串的副本,忽略前导空白和尾部空白。
String trimmed = " Hello, World! ".trim(); // trimmed will be "Hello, World!"
split(String regex): 使用指定的正则表达式将字符串分割成子字符串数组。
String[] parts = str.split(", "); // parts will be ["Hello", "World!"]
replace(char oldChar, char newChar): 返回一个新的字符串,其中所有的旧字符都被新的字符替换。
String replaced = str.replace('l', 'p'); // replaced will be "Heplo, Worpd!"
toLowerCase(): 将字符串中的所有字符转换为小写。
String lowerCaseStr = str.toLowerCase(); // lowerCaseStr will be "hello, world!"
toUpperCase(): 将字符串中的所有字符转换为大写。
String upperCaseStr = str.toUpperCase(); // upperCaseStr will be "HELLO, WORLD!"
trimToEmpty(): 如果字符串为空或仅包含空白字符,则返回空字符串; 否则,返回去掉前导和尾随空白后的字符串。
String emptyStr = "".trimToEmpty(); // emptyStr will be ""
这些方法只是Java字符串类提供的一部分功能。字符串是不可变的,所以每次对字符串进行操作时,都会创建一个新的字符串对象。在实际编程中,应该根据需要选择合适的方法来操作字符串。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。