如何从控制台中的字符串中删除字符

时间:2019-05-15 08:56:28

标签: c#

using System; 

class Strng { 

    // Main Method 
    public static void Main() 
    { 

        // define string 
        String str = "Some_String"; 

        Console.WriteLine("Given String : " + str); 

        // delete from index 5 to end of string 
        Console.WriteLine("New String1 : " + str.Remove(5)); 

        // delete character from index 8 to end of string 
        Console.WriteLine("New String2 : " + str.Remove(8)); 
    } 
} 

以上内容适用于给定的输入,但我想动态地提供输入并动态地从给定的字符串中删除字符

2 个答案:

答案 0 :(得分:2)

您似乎想动态读取要替换的字符串和字符。

您可以使用Console.ReadLine()Console.ReadKey()

在您的主要方法中实现以下内容:

Console.WriteLine("Enter a string:");
string s = Console.ReadLine();
Console.WriteLine("Enter a character to remove:");
string rs = Console.ReadLine().ToString();
//Assuming if they enter 'a' you want to remove both 'a' AND 'A':
string rsUpCase = rs.ToUpper();
string rsLoCase = rs.ToLower();
s = s.Replace(rsUpCase,"");     
s = s.Replace(rsLoCase,"");
Console.WriteLine(s);

//Input:
//Aardvarks are boring creatures
//Result:
//rdvrks re boring cretures

将允许用户动态输入字符串(不进行硬编码)并利用Replace函数删除任何字符-还演示了使用大写/小写来确定是否要同时使用两个变体要删除的字符。

希望这会有所帮助。

答案 1 :(得分:1)

我认为正确的问题是如何从控制台读取。

您可以使用Console.Read()Console.ReadLine()

首先问这个字符串,然后问要删除的索引,如果这是动态

的意思

这是关于Read

的MSDN示例
using System;

class Sample 
{
    public static void Main() 
    {
    string m1 = "\nType a string of text then press Enter. " +
                "Type '+' anywhere in the text to quit:\n";
    string m2 = "Character '{0}' is hexadecimal 0x{1:x4}.";
    string m3 = "Character     is hexadecimal 0x{0:x4}.";
    char ch;
    int x;
//
    Console.WriteLine(m1);
    do  
        {
        x = Console.Read();
        try 
            {
            ch = Convert.ToChar(x);
            if (Char.IsWhiteSpace(ch))
               {
               Console.WriteLine(m3, x);
               if (ch == 0x0a) 
                   Console.WriteLine(m1);
               }
            else
               Console.WriteLine(m2, ch, x);
            }
        catch (OverflowException e) 
            {
            Console.WriteLine("{0} Value read = {1}.", e.Message, x);
            ch = Char.MinValue;
            Console.WriteLine(m1);
            }
        } while (ch != '+');
    }
}