Java字符串处理常见问题示例
在Java中,字符串处理是编程中常见的操作。以下是一些常见的字符串处理问题示例:
字符串拼接:
String str1 = "Hello";
String str2 = "World!";
String result = str1 + " " + str2; // 输出: Hello World!
字符串分割:
String sentence = "I love Java programming.";
String[] words = sentence.split(" "); // 按空格分词
for (String word : words) {
System.out.println(word); // 输出: I love Java programming.
}
字符串查找和替换:
```java
String str = “The quick brown fox jumps over the lazy dog.”;
// 查找字符串 “fox”
int index = str.indexOf(“fox”);
if (index != -1) {
System.out.println(“Found ‘fox’: “ + str.substring(index)); // 输出: Found ‘fox’: The quick brown fox jumps over the lazy dog.
}
// 替换字符串 “fox” 为 “cat”
str = str.replace(“fox”, “cat”);
System.out.println(“After replacing: “ + str); // 输出: After replacing: The quick brown cat jumps over the lazy dog.
```
以上就是Java中常见的一些字符串处理问题示例。
还没有评论,来说两句吧...