for 循环和 if-else 语句可以结合使用来对字符串中的字符进行条件判断和处理

2025-05-03ASPCMS社区 - fjmyhfvclm

在 Java 中,for 循环和 if-else 语句可以结合使用来对字符串中的字符进行条件判断和处理。下面是一个示例代码,演示如何使用 for 循环和 if-else 语句来遍历字符串,并根据字符的类型输出不同的信息:

java

public class Main {

public static void main(String[] args) {

String str = "Hello, World! 123";

// 使用 for 循环遍历字符串

for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);

// 使用 if-else 语句进行条件判断

if (Character.isLetter(ch)) {

System.out.println("Character at position " + i + " is a letter: " + ch);

} else if (Character.isDigit(ch)) {

System.out.println("Character at position " + i + " is a digit: " + ch);

} else {

System.out.println("Character at position " + i + " is neither a letter nor a digit: " + ch);

}

}

}

}

代码解释

字符串定义:

String str = "Hello, World! 123"; 定义了一个字符串 str,包含字母、标点符号和数字。

for 循环:

for (int i = 0; i < str.length(); i++):初始化一个索引变量 i,从 0 开始,直到 i 小于字符串的长度 `str.

全部评论