简体   繁体   中英

changing string dynamically in C#

When I'm putting the following code specifically in the immediate window in Visual studio, it returns correctly:

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

But when I put it in a program as shown below, it fails:-

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");

        }
    }
}

I was expecting "whatToMatch" to change dynamically as it is correct code, but it's not changing. Why? And how to resolve this issue?

From msdn about String.Remove Method (Int32, Int32)

It returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

So it doesn't modify the string that call it, it return a new string. So you should use

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

As already mentioned, strings in .NET are immutable, therefore you cannot expect your string to change dynamically.

Here is a concise solution to your problem using 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");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM