java 字符串操作
时间: 2024-01-12 21:22:16 浏览: 82
以下是Java中常见的字符串操作示例:
1. 字符串拼接
```java
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2; // 输出:Hello World
```
2. 字符串长度
```java
String str = "Hello";
int length = str.length(); // 输出:5
```
3. 字符串查找
```java
String str = "Hello World";
int index = str.indexOf("World"); // 输出:6
```
4. 字符串替换
```java
String str = "This is a String";
String newStr = str.replace("is", "was"); // 输出:Thwas was a String
```
5. 字符串分割
```java
String str = "Hello,World";
String[] parts = str.split(","); // parts = ["Hello", "World"]
```
6. 字符串转换为大写或小写
```java
String str = "Hello";
String upperCase = str.toUpperCase(); // 输出:HELLO
String lowerCase = str.toLowerCase(); // 输出:hello
```
7. 字符串去除首尾空格
```java
String str = " Hello ";
String trimmedStr = str.trim(); // 输出:Hello
```
阅读全文