-1

我不想要“charAt(1);” 返回字符串中位置 1 的字符...我希望它报告“matching = 1;”的所有实例

举个例子

int matching = 1;
int notMatching = 0;
int HI = matching;
int IH = notMatching; 
int searchString = theString.charAt(notMatching);

  int count = 0;
  int index = 0;

      while (0 < theString.length())
      {
      int  = theString.charAt(matching);
        if (theString.charAt(notMatching) == searchString)    
        {
        count = count + 1;
        }
        index = index + 1;
      }

不是一个很好的例子,但基本上是我想要的,或者这个程序应该做的是接受用户输入:

HIHIIH

并报告 HI 的实例拼写为 IH... 所以返回例如;

System.out.println("HI 拼写为 IH" + count + "times");

编辑:“重复”对我没有帮助

4

1 回答 1

0

您可以使用 StringBuffer 的 reverse 方法以及 Pattern 和 Matcher,如下所示:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SearchReverseString {
    public static void main(String []args) {
        String str = "HIHIIH";
        String strToSearch = "HI";
        String strToSearchReversed = new StringBuffer(strToSearch).reverse().toString();
        Pattern strPattern = Pattern.compile(Pattern.quote(strToSearchReversed));
        Matcher matcher = strPattern.matcher(str);
        int counter = 0;
        while(matcher.find()) {
            ++counter;
        }
        System.out.println(strToSearch+" was spelt as "+strToSearchReversed+" "+counter+" times");
    }
}

输出是:

HI 被拼写为 IH 2 次

请注意,在我的程序中,str 表示输入字符串,strToSearch 表示要以相反顺序搜索的字符串。Pattern.quote 的使用确保任何元字符都被自动转义。

于 2015-03-01T07:03:14.923 回答