gpt4 book ai didi

java - 检查字符串的结尾,无需使用 Java 中的endsWith() 等内置方法

转载 作者:行者123 更新时间:2023-12-01 22:21:07 25 4
gpt4 key购买 nike

我想检查字符串中的每个单词是否都有不同长度的特定结尾。我不能使用数组和方法,例如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;
}
}

实际结果是我少了一个,我猜是因为它没有正确检查最后一个字符。

最佳答案

我能想到的最简单的解决方案如下:

检查单词是否以给定后缀结尾:

public static boolean endsWith(String word, String suffix) {
if(suffix.length() > word.length()) {
return false;
}
int textIndex = (word.length() - 1);
int suffixIndex = (suffix.length() - 1);
while(suffixIndex >= 0) {
char textChar = word.charAt(textIndex);
char suffixChar = suffix.charAt(suffixIndex);
if(textChar != suffixChar) {
return false;
}
textIndex--;
suffixIndex--;
}
return true;
}

将给定的单词拆分,并使用上述方法来计算以给定结尾结尾的每个单词:

public static int countEndings(String text, String ending) {
{
//maybe remove punctuation here...
//(if yes, use String.replace for example)
}
String[] words = text.split(" ");
int counter = 0;
for(String word: words) {
if(endsWith(word, ending)) {
counter++;
}
}
return counter;
}

还要考虑删除不需要的标点符号,例如“!”或者 '?' (...) - 上述实现不会识别 String 中以 t 结尾的任何单词的计数 test!!

关于java - 检查字符串的结尾,无需使用 Java 中的endsWith() 等内置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com