计算单词和数字总和为什么不起作用?

时间:2018-12-15 17:09:10

标签: c#

任务: 程序要求用户输入文本,输入文本后,程序将声明文本中有多少个单词。它还会计算文本中的位数,并将其显示在屏幕上。

    static void Main(string[] args)
    {
        Console.Write("Insert text: ");

        string s = Console.ReadLine();
        int count = 1, num, sum = 0, r;
        for (int i = 1; i < s.Length; i++)
        {
            if (Char.IsWhiteSpace(s[i]))
            {
                count++;
            }
        }
        num = int.Parse(Console.ReadLine());
        while (num != 0)
        {
            r = num % 10;
            num = num / 10;
            sum = sum + r;
        }
        Console.WriteLine("Sum of Digits of the Number : " + sum);
        Console.WriteLine("In text {1} names", s, count);

    }

程序要求输入文本和数字。计数文本中的数字,为什么它不能正常工作?

2 个答案:

答案 0 :(得分:1)

根据注释中描述的输入/输出,您不需要第二条ReadLine语句。您可以执行以下操作。

static void Main(string[] args)
{
    Console.WriteLine("Enter Text");
    var userEntry = Console.ReadLine();
    var countOfWords = userEntry.Split(new []{" "},StringSplitOptions.RemoveEmptyEntries).Count();
    var sum = userEntry.Where(c => Char.IsDigit(c)).Select(x=>int.Parse(x.ToString())).Sum();
    Console.WriteLine($"Count Of Words :{countOfWords}{Environment.NewLine}Sum :{sum}");
}

在这种情况下(根据您的评论),输入字符串为“ xsad8 dlas8 dsao9”,其总和为25。

如果输入字符串为“ xsad8 dlas81 dsao9”,并且您希望将81视为“ 81”而不是8&1,则求和可以如下计算。

var sum = Regex.Split(userEntry, @"\D+").Where(s => s != String.Empty).Sum(x=>int.Parse(x));

上述情况的总和为98

答案 1 :(得分:0)

尝试此代码。希望对您有帮助。

using System;

namespace SimpleProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            // Task:
            // The program asks the user to enter the text, after 
            // entering the text, the program declares how many words
            // are in the text. It also counts the amount of digits in 
            // the text and displays it on the screen.

            Console.WriteLine("Enter a Text");
            string word = Console.ReadLine();
            int wordCount = 0;

            char[] wordsArray = word.ToCharArray();
            foreach (var item in wordsArray)
            {
                //Counting the number of words in array.
                wordCount = wordCount + 1;
            }

            Console.WriteLine("Entered Text: " + word);
            Console.WriteLine("No. of Counts: " + wordCount);

        }
    }
}