在C#中动态更改字符串

问题描述 投票:0回答:2

当我将以下代码专门放在Visual Studio的即时窗口中时,它会正确返回:

whatToMatch.Remove((whatToMatch.IndexOf(input[i])), 1)

但是当我把它放在如下所示的程序中时,它会失败: -

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

namespace IsPangram
{
    class Program
    {
        static void Main(string[] args)
        {
            string whatToMatch = "abcdefghijklmnopqrstuvwxyz";
            string input = Console.ReadLine().ToLower();
            for (int i = 0; i < input.Length; i++)
            {
                if (whatToMatch.Contains(input[i]))
                {
                    whatToMatch.Remove((whatToMatch.IndexOf(input[i])), 1);
                }
                if (whatToMatch.Length == 0)
                    Console.WriteLine("pangram");
            }
            Console.WriteLine("not pangram");

        }
    }
}

我期待“whatToMatch”能够动态改变,因为它是正确的代码,但它并没有改变。为什么?以及如何解决这个问题?

c# visual-studio
2个回答
0
投票

如前所述,.NET中的字符串是不可变的,因此您不能指望您的字符串动态更改。

以下是使用LINQ解决问题的简明解决方案:

using System;
using System.Collections.Generic;
using System.Linq;

namespace IsPangram
{
    static class Program
    {
        public static bool IsPangram(this string input)
        {
            return
                !input.ToLower()
                      .Aggregate("abcdefghijklmnopqrstuvwxyz".ToList(),
                                 (ts, c) => ts.Where(x => x != c).ToList())
                      .Any();
        }

        public static void Main(string[] args)
        {
            Console.WriteLine(Console.ReadLine().IsPangram() ?
                              "Is pangram" :
                              "Is not pangram");
        }
    }
}

1
投票

来自msdn关于String.Remove Method (Int32, Int32)

它返回一个新字符串,其中删除了从指定位置开始的当前实例中的指定数量的字符。

所以它不会修改调用它的字符串,它会返回一个新字符串。所以你应该使用

whatToMatch = whatToMatch.Remove((whatToMatch.IndexOf(input[i])), 1)
© www.soinside.com 2019 - 2024. All rights reserved.