String类的常用方法并附代码举例

String类是Java中最常用的类之一,它提供了许多方法来操作字符串。以下是一些常用的String类方法及其代码示例:

length():返回字符串的长度。

String str = "Hello World";
int length = str.length();
System.out.println("Length: " + length); // 输出:Length: 11

charAt(int index):返回指定索引处的字符。

String str = "Hello World";
char ch = str.charAt(4);
System.out.println("Character at index 4: " + ch); // 输出:Character at index 4: o

substring(int beginIndex, int endIndex):返回一个新字符串,它是此字符串的一个子字符串。

String str = "Hello World";
String subStr = str.substring(6, 11);
System.out.println("Substring from index 6 to 10: " + subStr); // 输出:Substring from index 6 to 10: World

indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引。

String str = "Hello World";
int index = str.indexOf("World");
System.out.println("Index of 'World': " + index); // 输出:Index of 'World': 6

lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引。

String str = "Hello World World";
int lastIndex = str.lastIndexOf("World");
System.out.println("Last index of 'World': " + lastIndex); // 输出:Last index of 'World': 12

​​​​​​​equals(Object obj):比较两个字符串的内容是否相等。

String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2);
System.out.println("Are the strings equal? " + isEqual); // 输出:Are the strings equal? true

​​​​​​​compareTo(String anotherString):按字典顺序比较两个字符串。

String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
if (result < 0) {
    System.out.println(str1 + " comes before " + str2); // 输出:apple comes before banana
} else if (result > 0) {
    System.out.println(str1 + " comes after " + str2); // 输出:apple comes after banana
} else {
    System.out.println(str1 + " is equal to " + str2); // 输出:apple is equal to apple
}

​​​​​​​toLowerCase():将所有字符转换为小写。

String str = "Hello World";
String lowerStr = str.toLowerCase();
System.out.println("Lowercase string: " + lowerStr); // 输出:Lowercase string: hello world

​​​​​​​toUpperCase():将所有字符转换为大写。

String str = "Hello World";
String upperStr = str.toUpperCase();
System.out.println("Uppercase string: " + upperStr); // 输出:Uppercase string: HELLO WORLD

​​​​​​​trim():去除字符串两端的空格。

String str = " Hello World ";
String trimmedStr = str.trim();
System.out.println("Trimmed string: " + trimmedStr); // 输出:Trimmed string: Hello World

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值