我如何在两个if语句之间创建两个for循环,只要其中包含两个重复出现的字母,该语句将仅接受该单词? [英] How do i create two for loops with an if statement inbetween that will only accept the word aslong as it has two reoccuring letters in it?
问题描述
int i = 0;
// int j = i + 1;
int charCount = 0;
for(i=0; i<word.Length;i++)
{
for ( int j= 1; i < word.Length; j++)
{
if(word.Substring(i)==word.Substring(j))
{
charCount++;
}
}
}
if (charCount!=0)
MessageBox.Show("Word Accepted");
else
MessageBox.Show("Word Accepted");
推荐答案
您所拥有的几乎是正确的主意. 但是,有两个问题.
What you have is close to the right idea. However, there are a couple of problems.
1.除了第一个字符外,您还要将每个字母与其自身进行比较. 因此,您将把word [1]与word [1]进行比较,很可能会匹配.
1. Except for the very first character, you're going to compare each letter to itself. So, you'll compare word[1] to word[1], and that's very likely going to match.
2.调用word.Substring(i)返回从元素i开始的其余字符串.
2. The call word.Substring(i) returns the rest of the string starting at element i.
因此,如果您执行以下操作:
So, if you do something like:
for(i = 0; i< word.Length-1; i ++)
for(j = i + 1; j< word.Length; j ++)
if(word [i] == word [j])
charCount ++;
for( i = 0; i < word.Length-1; i++ )
for( j = i+1; j < word.Length; j++ )
if( word[i] == word[j] )
charCount++;
这应该可以满足您的要求.
that should just about do what you want.
这篇关于我如何在两个if语句之间创建两个for循环,只要其中包含两个重复出现的字母,该语句将仅接受该单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!