首页 > 解决方案 > C# 局部变量不会在 if 语句中发生变异

问题描述

我是 C# 的新手,我已经用谷歌搜索了答案。我找到的最接近的答案是这个。但这对我没有帮助。

我正在尝试编写一个函数,该函数仅使用循环和拼接来查找字符串中的最大数字。由于某种原因,当条件满足时,局部变量 big 不会在 if 语句中发生变化。我试图通过设置 big = 34 来调试它,当我点击一个空格时,但即使这样它也不会改变局部变量。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace parser
{
    class Sub_parser
    {
        // function to find the greatest number in a string
        public int Greatest(string uinput)
        {
            int len = uinput.Length;
            string con1 = "";
            int big = 0;
            int m = 0;

            // looping through the string
            for (int i = 0; i < len; i++)
            {
                // find all the numbers
                if (char.IsDigit(uinput[i]))
                {
                    con1 = con1 + uinput[i];
                }

                // if we hit a space then we check the number value
                else if (uinput[i].Equals(" ")) 
                {
                    if (con1 != "")
                    {
                        m = int.Parse(con1);
                        Console.WriteLine(m);
                        if (m > big)
                        {
                            big = m;
                        }
                    }

                    con1 = "";

                }

            }

            return big;
        }
        public static void Main(string[] args)
        {
            while (true)
            {
                string u_input = Console.ReadLine();
                Sub_parser sp = new Sub_parser();
                Console.WriteLine(sp.Greatest(u_input));
            }

        }
    }
}

标签: c#

解决方案


问题来自您在此声明中的检查:

else if (uinput[i].Equals(" "))

uinput[i] 是一个字符,而 "" 是一个字符串:看这个例子

如果你用单引号替换双引号,它工作正常......

else if (uinput[i].Equals(' '))

而且,正如评论所述,永远不会检查最后一个数字,除非您的输入字符串以空格结尾。这使您有两个选择:

  • 循环后再次检查con1的值(不是很好看)
  • 重写你的方法,因为你有点过头了,不要重新发明轮子。您可以执行以下操作(使用 System.Linq):

    public int BiggestNumberInString(string input)
    {
        return input.Split(null).Max(x => int.Parse(x));
    }
    

    只有当你确定你的输入


推荐阅读