我的C#For Loop和If声明出了什么问题?
发布时间:2020-12-16 10:29:25 所属栏目:百科 来源:网络整理
导读: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"; }} 所以,我正
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<)部分的第二部分. 但我的问题是它根本没有注册“if letter ==”g“”.因为根据我的本地窗口,它说letter = Debugging,这会让我觉得g应该在我的程序上注册24次,我想(因为str.length是9个字母长?)但是无论什么是什么都注册为0我做. 解决方法
您正在提取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++; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |