简体   繁体   English

字符串中的最后一个单词和第一个单词 c#

[英]last and first word in a string c#

i need to print the first and the last word in a string here is what i've tried我需要打印字符串中的第一个和最后一个单词这是我尝试过的

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

when i run the code this massage appear当我运行代码时,这个按摩出现

Unhandled Exception: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.未处理的异常:System.ArgumentOutOfRangeException:索引和长度必须引用字符串中的位置。 Parameter name: length at System.String.Substring(Int32 startIndex, Int32 length) at ConsoleApp1.Tar13.Main() in C:\Users\User\source\repos\ConsoleApp1\ConsoleApp1\Tar13.cs:line 16参数名称:C:\Users\User\source\repos\ConsoleApp1\ConsoleApp1\Tar13.cs:line 16 中 ConsoleApp1.Tar13.Main() 处 System.String.Substring(Int32 startIndex, Int32 length) 的长度

i dont know what is the problem我不知道是什么问题

If this is homework, don't hand this in unless you really understand it, have done LINQ (or have a supervisor that approves of off-piste learning and you're prepared to acknowledge you got outside assistance/did background learning) and are willing to explain it if asked:如果这是家庭作业,除非你真的理解它,否则不要提交它,已经完成了 LINQ(或者有一个批准越野学习的主管并且你准备承认你得到了外部帮助/进行了背景学习)并且是如果被问到愿意解释

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

For a non-LINQ version:对于非 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);

Bear in mind that these will crash if there are no spaces in the string - the Split version won't请记住,如果字符串中没有空格,这些将崩溃 - 拆分版本不会

Look at String Remove and Substring查看字符串删除Substring

If you want to robust things up so it doesn't crash:如果您想增强功能使其不会崩溃:

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

I'll leave a "what might we put in an else ?"我会留下“我们可以在else中放什么?” in that last code block, as an exercise for you:)在最后一个代码块中,作为你的练习:)

you can split the string and get first and last...您可以拆分字符串并获取第一个和最后一个...

   var s = str.Split(' ', StringSplitOptions.RemoveEmptyEntries );
   if(s.Length >= 2) 
   {
    var first = s.First();
    var last = s.Last();
    Console.WriteLine($"{first} {last}");
   }

In general case when sentence can contain punctuation , not necessary English letters you can try regular expressions .一般情况下,当句子可以包含标点符号,不需要英文字母时,可以试试正则表达式 Let's define让我们定义

Word is non empty sequence of letters and apostrophes Word字母撇号的非空序列

And so we have所以我们有

Code:代码:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  private static (string first, string last) Solve(string value) {
    if (string.IsNullOrWhiteSpace(value))
      return ("", "");

    var words = Regex
      .Matches(value, @"[\p{L}']+")
      .Cast<Match>()
      .Select(m => m.Value)
      .ToArray();

    return words.Length > 0
      ? (words[0], words[words.Length - 1])
      : ("", ""); 
  }

Demo:演示:

  string[] tests = new string[] {
    "Simple string",                 // Simple Smoke Test
    "Single",                        // Single word which is both first an last
    "",                              // No words at all; let's return empty strings
    "words, punctuations: the end.", // Punctuations
    "Русская (Russian) строка!",     // Punctuations, non-English words
  };

  var result = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-30} :: {Solve(test)}"));

  Console.Write(result);

Outcome:结果:

Simple string                  :: (Simple, string)
Single                         :: (Single, Single)
                               :: (, )
words, punctuations: the end.  :: (words, end)
Русская (Russian) строка!      :: (Русская, строка)

If you want to get the last and first-word try to do the following:如果您想获取最后一个单词和第一个单词,请尝试执行以下操作:

string sentence = "Hello World"; //Sentence
string first = sentence.Split(" ")[0]; //First word
string last = sentence.Split(" ")[sentence.Split(" ").Length -1]; //Last word
Console.WriteLine(first + " "+ last);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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