java如何遍历字符串
时间: 2023-08-10 21:05:43 浏览: 89
在Java中,可以使用多种方法遍历字符串。以下是几种方法:
1. 使用for循环遍历字符串中的每个字符。
```java
String str = "Hello World!";
for(int i=0; i<str.length(); i++){
char c = str.charAt(i);
System.out.print(c + " ");
}
```
2. 使用foreach循环遍历字符串中的每个字符。
```java
String str = "Hello World!";
for(char c : str.toCharArray()){
System.out.print(c + " ");
}
```
3. 使用Java 8中的Stream API遍历字符串中的每个字符。
```java
String str = "Hello World!";
str.chars().mapToObj(c -> (char) c).forEach(System.out::print);
```
无论使用哪种方法,都可以遍历字符串中的每个字符。
相关问题
Java遍历字符串
在Java中,可以使用以下几种方式遍历字符串:
1. for循环
使用for循环遍历字符串,可以使用String.charAt()方法获取字符串指定位置的字符。例如:
```
String str = "Hello World!";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
System.out.print(c + " ");
}
```
输出:
```
H e l l o W o r l d !
```
2. 增强for循环
使用增强for循环遍历字符串,可以直接遍历字符串中的每个字符。例如:
```
String str = "Hello World!";
for (char c : str.toCharArray()) {
System.out.print(c + " ");
}
```
输出:
```
H e l l o W o r l d !
```
3. 迭代器
使用迭代器遍历字符串,可以使用String.chars()方法获取一个IntStream流,再使用IntStream.mapToObj()方法将每个字符转换成Character对象,最后使用迭代器遍历Character对象。例如:
```
String str = "Hello World!";
Iterator<Character> iterator = str.chars()
.mapToObj(c -> (char) c)
.iterator();
while (iterator.hasNext()) {
char c = iterator.next();
System.out.print(c + " ");
}
```
输出:
```
H e l l o W o r l d !
```
以上是几种常用的遍历字符串的方式,需要根据实际情况选择合适的方式。
java遍历字符串,用逗号拼接
你可以使用 StringBuilder 或者 StringJoiner 类来遍历字符串并用逗号拼接。以下是使用 StringBuilder 的示例代码:
```java
String input = "abcde";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < input.length(); i++) {
sb.append(input.charAt(i));
if(i != input.length() - 1) {
sb.append(",");
}
}
String output = sb.toString();
System.out.println(output);
```
输出结果为:`a,b,c,d,e`。
如果你使用 Java 8 或更高版本,也可以使用 StringJoiner 类来实现:
```java
String input = "abcde";
StringJoiner joiner = new StringJoiner(",");
for(int i = 0; i < input.length(); i++) {
joiner.add(String.valueOf(input.charAt(i)));
}
String output = joiner.toString();
System.out.println(output);
```
输出结果同样为:`a,b,c,d,e`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)