c# - 删除最后一个字母后的所有字符

标签 c# visual-studio-2010

以下简单程序将找到用户输入的字符串中的最后一个字母,然后删除该点之后的所有字母。所以,如果一个人输入一个 string....g 之后的所有内容都应该被删除。我有以下小程序:

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter in the value of the string: ");
        List<char> charList = Console.ReadLine().Trim().ToList();

        int x = charList.LastIndexOf(charList.Last(char.IsLetter)) ;
        Console.WriteLine("this is the last letter {0}", x);
        Console.WriteLine("This is the length of the string {0}", charList.Count);
        Console.WriteLine("We should have the last {0} characters removed", charList.Count - x);

        for (int i = x; i < charList.Count; i++)
        {
            charList.Remove(charList[i]);
        }

        foreach (char c in charList)
        {
            Console.Write(c);
        }
        Console.ReadLine();
    }
}

我已经尝试了很多变体,但没有一个能准确地写出来。这个输入为 string.... 的特定程序程序的输出是 strin.. 所以不知何故它留下了它应该带走的东西并且它实际上正在带走去掉不应该的字母。谁能说明为什么会这样?所需的输出,同样应该是 string

最佳答案

试试这个:

string input = Console.ReadLine();                // ABC.ABC.
int index = input.Select((c, i) => new { c, i })
                 .Where(x => char.IsLetter(x.c))
                 .Max(x => x.i);
string trimmedInput = input.Substring(0, index + 1);
Console.WriteLine(trimmedInput);                  // ABC.ABC

关于c# - 删除最后一个字母后的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16279141/

相关文章:

vb.net - VB 2010 将 UTC 日期转换为 dd-MMM-yyyy 格式

visual-studio-2010 - TFS 比较选项

c++ - 奇怪的是 VS2010 中反复出现的模板模式错误?

c# - Entity Framework - 在程序集中找不到迁移配置类型

c# - 我可以使用 set 方法代替 Json 属性吗?

c# - VS2013 调试/Windows/任务 : "No tasks to display"

c++ - 微软的OpenMP自旋锁时间如何控制?

c# - 如何让 msbuild 在 vi​​sual studio 中部署任务?

c# - 使用 FedEx 运送服务 WSDL 创建 FedEx 运送文件

visual-studio-2010 - 使用 Visual Studio 的调试器查看动态分配的空终止字符串