我的C#For Loop和If声明出了什么问题?

时间:2011-06-13 21:54:17

标签: c# .net

int LetterCount = 0;
string strText = "Debugging";
string letter;

for (int i = 0; i <strText.Length; i++)
{
  letter = strText.Substring(0, 9);
  if(letter == "g")
  {    
    LetterCount++;
    textBox1.Text = "g appears " + LetterCount + " times";
  }
}

所以,我正在做这个教程的事情,而且我已经坚持这个练习4个小时了。我无法弄清楚我的For循环有什么问题。

练习的目的是让我的程序告诉我调试这个词有多少g。但你可能已经想到了这一点。无论如何,我甚至不确定我是否有正确的代码告诉我,因为我认为我需要更改For循环(i&lt;)部分的第二部分。

但我的问题是它根本没有注册“if letter ==”g“”。因为根据我的本地窗口,它说letter = Debugging,这会让我认为g应该在我的程序上注册24次,我想(因为str.length是9个字母长?)但它注册为0否不管我做什么。

10 个答案:

答案 0 :(得分:7)

您正在提取9个字符的字符串。它永远不会等于“g”(只有一个)。我就是这样做的。

int count = 0;
foreach (char c in strText)
{
    if (c == 'g')
       count++;
}

使用for循环:

for (int i = 0; i < strText.Length; i++)
{
    if (strText[i] == 'g')
       count++;
}

答案 1 :(得分:5)

查看string.Substring(x, y)的文档。

基本上:

letter = strText.Substring(0, 9);

没有给你一封信。每次通过它都会给你字符串strText的所有9个字符。 您可能需要考虑将变量i用于传递给Substring的其中一个值。

(我故意没有给你完整的答案,因为你似乎想要理解,所以,如果我给出的指示不能让你到那里,请告诉我,我会扩展我的回答=)

答案 2 :(得分:1)

试试这个:

    for (int i = 0; i <strText.Length; i++)
    {

       if(strText[i] == 'g')
       {
         LetterCount++;
       }
    }
    textBox1.Text = "g appears " + LetterCount + " times";

问题是,当您与“g”进行比较时,您正在查看整个字符串。通过指定索引,您可以告诉它查看字符串中的特定字符。另外,我删除了你的子串,因为它似乎没有做任何事情。

答案 3 :(得分:0)

您在i循环中根本没有使用for

你的意思是

letter = strText.Substring(i, 1);

答案 4 :(得分:0)

好吧,您正在使用长9个字符的子字符串并将其与“g”进行比较。它不会是平等的。

你应该尝试:

letter = strText.Substring(i,1);

答案 5 :(得分:0)

因为String.Substring(int, int)有两个参数:偏移和要采取的数量。

在您的情况下,letter = strText.Substring(0, 9);只会将字母值分配给“调试”。如果您想单独检查每个字母,则需要写letter = strText.Substring(i, 1)

答案 6 :(得分:0)

你可能正在寻找这样的东西:

int LetterCount = 0;
string strText = "Debugging";
string letter;

for (int i = 0; i <strText.Length; i++)
{
  letter = strText.Substring(i, 1);
  if(letter == "g")
  {    
    LetterCount++;
    textBox1.Text = "g appears " + LetterCount + " times";

  }
}

答案 7 :(得分:0)

letter = strText.Substring(0,9);

此时,'letter'的值为“Debugging”,因为你正在取整个字符串。

尝试letter = strText[i],以便隔离单个字母。

答案 8 :(得分:0)

@Rob说的是什么。

尝试这样的事情:

int    gCount = 0;
string s      = "Debugging";

for ( int i = 0; i <strText.Length; i++)
{
  if ( s[i] == 'g' ) ++gCount ;
}
textBox1.Text = "g appears " + gCount+ " times";

答案 9 :(得分:0)

namespace runtime
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            int lettercount = 0;
            string strText = "Debugging";
            string letter;


            for (int i = 0; i < strText.Length; i++)
            {
                letter = strText.Substring(i,1);

                if (letter == "g")
                {
                    lettercount++;
                }

            }
            textBox1.Text = "g appear " + lettercount + " times";
        }
    }
}