在C#中动态更改字符串

时间:2018-02-28 08:02:03

标签: c# visual-studio

当我将以下代码专门放在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");

        }
    }
}

我期待&#34; whatToMatch&#34;因为它是正确的代码而动态更改,但它没有改变。为什么?以及如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

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

  

返回一个新字符串,其中包含指定数量的字符   从指定位置开始的当前实例已经存在   删除。

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

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

答案 1 :(得分: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");
        }
    }
}