Java程序遍历字符串的每个字符。
在本文中,我们将了解如何使用Java遍历字符串的每个字符。字符串是一种数据类型,包含一个或多个字符,并用双引号(“ ”)括起来。字符是一种数据类型,包含字母、整数或特殊字符。
问题陈述
编写一个程序来遍历字符串的每个字符。以下是相同的演示:
输入
The string is defined as: Java Program
输出
The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
不同的方法
以下是遍历字符串中每个字符的不同方法:
使用for循环遍历字符串的每个字符
以下是使用for循环遍历字符串中每个字符的步骤:
- 定义一个字符串变量input_string,其值为"Java Program"。
- 使用print语句打印定义的字符串。
- 使用for循环遍历字符串的每个字符。
- 使用charAt()方法通过索引获取字符串的每个字符。
- 打印每个字符,后跟逗号。
- 打印所有字符后结束循环。
示例
以下是用for循环遍历字符串中每个字符的示例:
public class Characters {
public static void main(String[] args) {
String input_string = "Java Program";
System.out.println("The string is defined as: " +input_string);
System.out.println("The characters in the string are: ");
for(int i = 0; i<input_string.length(); i++) {
char temp = input_string.charAt(i);
System.out.print(temp + ", ");
}
}
}
输出
The string is defined as: Java Program The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
使用forEach循环遍历字符串的每个字符
以下是使用forEach循环遍历字符串中每个字符的步骤:
- 定义一个字符串变量input_string,其值为"Java Program"。
- 使用print语句打印定义的字符串。
- 使用toCharArray()方法将字符串转换为字符数组。
- 使用forEach循环遍历数组中的每个字符。
- 打印每个字符,后跟逗号。
示例
以下是用forEach循环遍历字符串中每个字符的示例:
public class Main {
public static void main(String[] args) {
String input_string = "Java Program";
System.out.println("The string is defined as: " +input_string);
System.out.println("The characters in the string are: ");
for(char temp : input_string.toCharArray()) {
System.out.print(temp + ", ");
}
}
}
输出
The string is defined as: Java Program The characters in the string are: J, a, v, a, , P, r, o, g, r, a, m,
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP