我不想要“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”+计数+“次”);
编辑:“复制”对我没有帮助
答案 0 :(得分:0)
您可以使用StringBuffer的反向方法和Pattern and 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表示输入String,strToSearch表示要按相反顺序搜索的String。使用Pattern.quote可确保自动转义任何元字符。