Java函数—如何处理字符串
发布时间:2023-06-29 18:36:35
在Java中,有很多方法可以处理字符串。以下是一些常见的字符串处理方法:
1. 获取字符串长度:可以使用String类的length()方法,例如:
String str = "Hello World";
int length = str.length();
System.out.println("字符串长度为:" + length);
2. 比较字符串是否相等:可以使用String类的equals()方法,例如:
String str1 = "Hello";
String str2 = "World";
boolean isEqual = str1.equals(str2);
System.out.println("两个字符串是否相等:" + isEqual);
3. 连接字符串:可以使用加号操作符(+)或者String类的concat()方法,例如:
String str1 = "Hello";
String str2 = "World";
String str3 = str1 + " " + str2;
System.out.println("连接后的字符串:" + str3);
String str4 = str1.concat(str2);
System.out.println("连接后的字符串:" + str4);
4. 判断字符串是否包含子字符串:可以使用String类的contains()方法,例如:
String str = "Hello World";
boolean contains = str.contains("World");
System.out.println("字符串是否包含子字符串:" + contains);
5. 获取子字符串:可以使用String类的substring()方法,例如:
String str = "Hello World";
String substr = str.substring(0, 5);
System.out.println("获取的子字符串:" + substr);
6. 字符串分割:可以使用String类的split()方法,例如:
String str = "Hello,World";
String[] parts = str.split(",");
System.out.println("分割后的字符串数组:");
for (String part : parts) {
System.out.println(part);
}
7. 替换字符串中的字符:可以使用String类的replace()方法,例如:
String str = "Hello World";
String replacedStr = str.replace("World", "Java");
System.out.println("替换后的字符串:" + replacedStr);
8. 字符串转换为大写或小写:可以使用String类的toUpperCase()和toLowerCase()方法,例如:
String str = "Hello World";
String upperCaseStr = str.toUpperCase();
System.out.println("大写字符串:" + upperCaseStr);
String lowerCaseStr = str.toLowerCase();
System.out.println("小写字符串:" + lowerCaseStr);
这只是一部分常见的字符串处理方法,Java中还有其他很多字符串处理方法。根据具体需求,选择合适的方法进行字符串处理。
