检查没有内置方法(如Java中的endsWith())的字符串的结尾

检查没有内置方法(如Java中的endsWith())的字符串的结尾,java,string,char,Java,String,Char,我想检查字符串中的每个单词是否都有不同长度的特定结尾。我不能像endsWith()那样使用数组和方法。我只允许使用charAt()和length()方法 公共类文本分析{ 公共静态void main(字符串[]args){ System.out.println(countEndings(“这是一个测试”,“t”)); System.out.println(countEndings(“Waren sollen rollen”,“en”); System.out.println(countEndin

我想检查字符串中的每个单词是否都有不同长度的特定结尾。我不能像endsWith()那样使用数组和方法。我只允许使用charAt()和length()方法

公共类文本分析{
公共静态void main(字符串[]args){
System.out.println(countEndings(“这是一个测试”,“t”));
System.out.println(countEndings(“Waren sollen rollen”,“en”);
System.out.println(countEndings(“结尾比每个单词都长”,“abcdefghijklmn”));
System.out.println(countEndings(“今天是个好日子”,“xyz”);
System.out.println(countEndings(“这是一个测试”,“t”));
System.out.println(countEndings(“这是一个测试!”,“t”);
System.out.println(countEndings(“这是测试吗?”,“t”);
}
公共静态int countEndings(字符串文本,字符串结尾){
int计数器=0;
整数计数;
int-lastStringChar;
对于(int i=0;i='A'&&text.charAt(i)='A'&&text.charAt(i)end.length();j++){
if(text.charAt(i-ending.length()+j+lastStringChar)==ending.charAt(j)){
计数=1;
}否则{
计数=0;
}
}
计数器+=计数;
}
}
返回计数器;
}
}

实际结果是,我得到了一个计数较少的结果,我想这是因为它没有正确地检查最后的字符。

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

如果单词以给定后缀结尾,请选中:

公共静态布尔值endsWith(字符串字、字符串后缀){
if(后缀.length()>word.length()){
返回false;
}
int textIndex=(word.length()-1);
int-suffixIndex=(后缀.length()-1);
while(后缀索引>=0){
char textChar=word.charAt(textIndex);
char-suffixChar=后缀.charAt(suffixIndex);
if(textChar!=后缀字符){
返回false;
}
文本索引--;
后缀索引--;
}
返回true;
}
将给定的单词拆分为“单词”,并使用上述方法计算以给定结尾的每个单词:

公共静态int countEndings(字符串文本,字符串结尾){
{
//也许删除这里的标点符号。。。
//(如果是,请使用String.replace作为示例)
}
String[]words=text.split(“”);
int计数器=0;
for(字符串字:字){
if(endsWith(单词,结尾)){
计数器++;
}
}
返回计数器;
}

也考虑删除不必要的标点符号,如“!”或“…”(…)-上述的实现将不会识别在<代码>字符串 <代码>测试> <代码> < /P> > P> >中的任何单词以“结束”结尾。 如果要计算带结尾的单词,可以使用以下代码:

public static int countEndings(String text, String ending) {
    final Matcher wordWithEndMatches = Pattern.compile("\\b[A-Za-z]*" + ending + "\\b").matcher(text);
    int count = 0;
    while(wordWithEndMatches.find()) {
        count++;
    }
    return count;
}

从最后一个字符开始,检查两个字符串是否匹配。是否允许使用
子字符串
等于
?:-DOr,更好,
区域匹配
?@T.J.Crowder应该检查该字符串中以字母“T”结尾的单词数,在这种情况下,它应该是一个。遗憾的是,我不允许使用这种方法:D@DavidDo2015-好的,这很有意义。我会将字符串拆分为一个单词数组,然后循环该数组。在任何情况下,在试图找出代码不起作用的原因时,最好的办法是使用IDE中内置的调试器逐条检查代码语句.
public static int countEndings(String text, String ending) {
    final Matcher wordWithEndMatches = Pattern.compile("\\b[A-Za-z]*" + ending + "\\b").matcher(text);
    int count = 0;
    while(wordWithEndMatches.find()) {
        count++;
    }
    return count;
}