[英]Count how many times a character changes in a string
我将此字符串作为示例的输入:
string value = "fffeefef";
我的问题是,我不知道该怎么办。 我想计算字符串中从f更改为e的次数,反之亦然,输出应该为4。字符串可能会更改,因此我无法弄清楚算法。 如果你们能启发我,我将不胜感激! 我知道这听起来很简单,但我仍在学习。 任何帮助表示赞赏!
编辑:根据要求添加注释以解释每个部分。
string value = "fffeefef"; // Set some value to use in the example
int counter = 0; // Initialize the counter, still zero changes found
for (int i = 1; i < value.Length; i++) // Make a loop, iterating for every char in the string
{
if (value[i - 1] != value[i]) // Compare every char with the previous char, starting at char 1 (the second char, as first position is zero).
counter++; // If the chars are different, increase our counter
}
参见示例: https : //dotnetfiddle.net/9vvlNw
string stringValue = "fffeefef";
int characterChanges = 0;
for(int i = 1; i < stringValue.Length; i++)
{
if(stringValue[i] != stringValue[i - 1])
{
characterChanges++;
}
}
Console.WriteLine("Character changed {0} times.", characterChanges);
字符串只是一个字符数组,因此您可以通过索引访问它们。 我们创建一个简单的for循环,该循环重复n - 1
次(因为我们从1开始),其中n
是stringValue
( stringValue.Length
)的长度。 我们的if语句表明,如果当前字符不等于当前字符,则增加一个计数器( characterChanges
)。
for循环的第一次迭代将显示为:是索引2处的字符等于索引1处的字符,然后是字符3处等于字符2的,依此类推...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.