【发布时间】:2019-10-28 10:35:25
【问题描述】:
我想检查字符串中的每个单词是否都有不同长度的特定结尾。我不能为此使用数组和方法,比如endsWith()。我允许使用的唯一方法是 charAt() 和 length()。
public class TextAnalyse {
public static void main(String[] args) {
System.out.println(countEndings("This is a test", "t"));
System.out.println(countEndings("Waren sollen rollen", "en"));
System.out.println(countEndings("The ending is longer then every single word", "abcdefghijklmn"));
System.out.println(countEndings("Today is a good day", "xyz"));
System.out.println(countEndings("Thist is a test", "t"));
System.out.println(countEndings("This is a test!", "t"));
System.out.println(countEndings("Is this a test?", "t"));
}
public static int countEndings(String text, String ending) {
int counter = 0;
int counting;
int lastStringChar;
for (int i = 0; i < text.length(); i++) {
lastStringChar = 0;
if (!(text.charAt(i) >= 'A' && text.charAt(i) <= 'Z' || text.charAt(i) >= 'a' && text.charAt(i) <= 'z') || i == text.length() - 1) {
if( i == text.length() - 1 ){
lastStringChar = 1;
}
counting = 0;
for (int j = 0; j + lastStringChar < ending.length() && i > ending.length(); j++) {
if (text.charAt(i - ending.length() + j + lastStringChar) == ending.charAt(j)) {
counting = 1;
} else {
counting = 0;
}
}
counter += counting;
}
}
return counter;
}
}
实际结果是我少了一个,我猜是因为它没有正确检查最后一个字符。
【问题讨论】:
-
从最后一个字符开始,通过两个字符串检查对应的字符是否匹配。
-
你可以使用
substring和equals吗? :-D -
或者,更好的是
regionMatches? -
@T.J.Crowder 它应该检查该字符串中有多少单词以字母“t”结尾,在这种情况下它应该是一个。可悲的是我不允许使用该方法:D
-
@DavidDo2015 - 好的,这是有道理的。我将字符串拆分为一个单词数组,然后循环该数组。在任何情况下,当你试图找出你的代码为什么不工作时,最好的办法是使用你的 IDE 中内置的调试器逐个语句地检查代码。