【问题标题】:How can I count how many lowercase, uppercase and other characters I have in my string properly?如何正确计算字符串中有多少个小写、大写和其他字符?
【发布时间】:2015-06-04 01:27:53
【问题描述】:

我的代码在这里表示所有小写和大写字母的计数,但我无法计算所有其他字符。其他字符由空格和符号组成,例如 '!@$^%$'。任何不是小写或大写的都指其他。

但是,我的问题是我的另一个是大写字母,我似乎无法计算出代码。

我不知道我哪里出错了,所以任何帮助将不胜感激,谢谢!

Console.WriteLine("Enter a sentence: ");
string sentence = Console.ReadLine();
int countUpper = 0, countLower=0, countOther=0, i;



        for (i = 0; i < sentence.Length;i++ )
        {
            if (char.IsUpper(sentence[i])) countUpper++;
            if (char.IsLower(sentence[i])) countLower++;
            if (!(char.IsLower(sentence[i]) || (!(char.IsUpper(sentence[i]))))) countOther++;

        }
        Console.WriteLine("Lower: " + countLower);
        Console.WriteLine("Upper: " + countUpper);
        Console.WriteLine("Other: " + countOther);

【问题讨论】:

  • || 更改为&amp;&amp;
  • if (! ((char.IsLower(sentence[i]) || (char.IsUpper(sentence[i]) )))
  • 考虑也使用foreach(char character in sentence) { if (char.IsUpper(character)) ... 您希望对一组字符进行操作,因此无需涉及indexers的所有机制。

标签: c# uppercase lowercase


【解决方案1】:

尝试改用if / else if / else

Console.WriteLine("Enter a sentence: ");
string sentence = Console.ReadLine();
int countUpper = 0, countLower=0, countOther=0, i;



        for (i = 0; i < sentence.Length;i++ )
        {
            if (char.IsUpper(sentence[i])) countUpper++;
            else if (char.IsLower(sentence[i])) countLower++;
            else countOther++;

        }
        Console.WriteLine("Lower: " + countLower);
        Console.WriteLine("Upper: " + countUpper);
        Console.WriteLine("Other: " + countOther);

【讨论】:

  • 我喜欢这个比修复逻辑更好,因为它减少了对 IsUpperIsLower 的调用次数。不知道为什么它被否决了。
【解决方案2】:

要计算特定字符,可以使用简单的Regex 代替逐个字符分析:

string sentence = "testTESTING@,";
int countLower = Regex.Matches(sentence, @"\p{Ll}").Count;
int countUpper = Regex.Matches(sentence, @"\p{Lu}").Count;
int countOther = Regex.Matches(sentence, @"\W").Count;

// \p{category} - In that Unicode category
// category = Lu - Letter, uppercase
// category = Ll - letter, lowercase
// \W = non word character

简单规范《.Net框架正则表达式快速参考》可从http://www.microsoft.com/en-us/download/details.aspx?id=43119下载

【讨论】:

    【解决方案3】:

    我认为countOther 就是string.Length - countUpper - countLower

    【讨论】:

    • 这将取决于文化。尽管您可能希望它是真的,但它不一定是真的。
    • 那么我将在他当前的代码中进行此更改 if (!(char.IsLower(sentence[i]) && (!(char.IsUpper(sentence[i]))))) countOther++ ;但是我想不出你所说的文化影响,你能举个例子吗?
    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 2014-10-03
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多