首页 > 解决方案 > 字符串c#中的最后一个单词和第一个单词

问题描述

我需要打印字符串中的第一个和最后一个单词这是我尝试过的

        Console.WriteLine("please enter a string");
        string str = Console.ReadLine();
        string first = str.Substring(0, str.IndexOf(" "));
        string last = str.Substring(str.LastIndexOf(' '),str.Length-1);
        Console.WriteLine(first + " " + last);

当我运行代码时,这个按摩出现

未处理的异常:System.ArgumentOutOfRangeException:索引和长度必须引用字符串中的位置。参数名称:C:\Users\User\source\repos\ConsoleApp1\ConsoleApp1\Tar13.cs:line 16 中 ConsoleApp1.Tar13.Main() 处 System.String.Substring(Int32 startIndex, Int32 length) 的长度

我不知道是什么问题

标签: c#string

解决方案


如果这是家庭作业,除非你真的理解它,否则不要交出它,已经完成了 LINQ(或者有一个批准越野学习的主管,并且你准备承认你得到了外部帮助/进行了背景学习)并且是如果被问到愿意解释:

    Console.WriteLine("please enter a string");
    string str = Console.ReadLine();
    string[] bits = str.Split();
    Console.WriteLine(bits.First() + " " + bits.Last());

对于非 LINQ 版本:

    Console.WriteLine("please enter a string");
    string str = Console.ReadLine();
    string first = str.Remove(str.IndexOf(' '));
    string last = str.Substring(str.LastIndexOf(' ') + 1);
    Console.WriteLine(first + " " + last);

请记住,如果字符串中没有空格,这些将崩溃 - 拆分版本不会

查看字符串删除子字符串

如果您想增强功能使其不会崩溃:

    Console.WriteLine("please enter a string");
    string str = Console.ReadLine();
    if(str.Contains(" ")){
      string first = str.Remove(str.IndexOf(' '));
      string last = str.Substring(str.LastIndexOf(' ') + 1);
      Console.WriteLine(first + " " + last);
    }

我会留下一个“我们可以在else中放什么?” 在最后一个代码块中,作为你的练习:)


推荐阅读