在我的 Java 程序中将符号识别为字符串的一部分?



我已经开始创建一个程序,用与大写单词长度匹配的星号替换大写字母单词。但是,在下面的示例中,您可以看到它将句号 (.( 视为单词的一部分。

有人可以向我解释为什么我的程序将句号(.(识别为字符串的一部分吗?

代码的输出是:

** was in *****

鉴于,我希望它是:

** was in ****.

public class redact {
public static void main(String args[]) {
/* String to split. */
String stringToSplit = "It was in July.";
String[] tempArray;
/* delimiter */
String delimiter = " ";
/* given string will be split by the argument delimiter provided. */
tempArray = stringToSplit.split(delimiter);
/* print substrings */
for (int i = 0; i < tempArray.length; i++) {
if (Character.isUpperCase(tempArray[i].charAt(0))) {
int length = tempArray[i].length();
tempArray[i] = "";
for(int j = 0; j < length; j++) {
tempArray[i] += ('*');
}   
System.out.print(" " + tempArray[i]);
} else {
System.out.print(" " + tempArray[i]);
}
// ----------------------------------------------------------------------------------------------
}
}
}

您将字符串拆分为空格。July.之间没有空格。tempArray[3]July.,而不是像你期望的那样July

执行所需操作的一种方法是检查单词的每个字符是否都是一个字母,然后将其替换为*。所以你需要保留tempArray的每个元素:

for (int i = 0; i < tempArray.length; i++) {
if (Character.isUpperCase(tempArray[i].charAt(0))) {
int length = tempArray[i].length();
//            tempArray[i] = "";
String result = "";
for(int j = 0; j < length; j++) {
if (Character.isLetter(tempArray[i].charAt(j))) {
result += ('*');
} else {
result += tempArray[i].charAt(j);
}
}
System.out.print(" " + result);
}
else {
System.out.print(" " + tempArray[i]);
}
}

最新更新