1

Thank you all for the help I have got it working with your help.

So I have written some code which extracts the first word within a string. Below is my code.

var LongString = "Hello World";
var firstWord = LongString.Substring(0, LongString.IndexOf(" "));

This code gives me the result "Hello" however how can I retrieve the last word from the string if I do not know the last index. Is there a method in which I can get the last index number without feeding it with a string that is currently within the LongString variable. Thanks in advance.

user9710070
  • 65
  • 1
  • 8
  • In your example, if you're looking for the index of `" "`, it will be the same. Can you further explain your needs? – Paul Karam Apr 27 '18 at 11:23
  • Would splitting on space work - you could then take the first & last array element. – PaulF Apr 27 '18 at 11:24
  • What you mean with _"feeding it with a string that is currently within the LongString variable"_ – Tim Schmelter Apr 27 '18 at 11:24
  • 2
    Possible duplicate of [Extract the last word from a string using C#](https://stackoverflow.com/questions/4603911/extract-the-last-word-from-a-string-using-c-sharp) – GSerg Apr 27 '18 at 11:26
  • @aponmene yes but if i were to use code for example var firstWord = LongString.Substring(0, LongString.LastIndexOf(" ")); would it return the expected World portion of the string? Sry im quite new to coding – user9710070 Apr 27 '18 at 11:26

4 Answers4

4
var lastWord = longString.Split(' ',
                                StringSplitOptions.RemoveEmptyEntries)
                         .Last();

That's about it.

InBetween
  • 32,319
  • 3
  • 50
  • 90
  • Saving the result of the Split operation would allow the first word & last word to be retrieved without need for the first Substring. – PaulF Apr 27 '18 at 11:27
  • @PaulF yes, if you are going to need to access different individual words more than once then caching the `Split` result is a must. – InBetween Apr 27 '18 at 11:28
3

Just use LastIndexOf.

const string hw = "Hello World";
var lastIndex = hw.LastIndexOf(" ");
Console.WriteLine(hw.Substring(lastIndex + 1));
0

If I understood correct you are looking for:

index = lastIndexLongString.LastIndexOf(" ");
var firstWord = LongString.Substring(index+1);
apomene
  • 14,282
  • 9
  • 46
  • 72
0

answer with running fix: use ' ' instead of " " for split function.

var splittedWord = LongString.Split(' ');
var firstWord = splittedWord.FirstOrDefault();
var secondWord = splittedWord.LastOrDefault();
  • I would set `var firstWord = splittedWord[0]` as String.Split returns an array of at least 1 string (even if the main string doesn't contains the separator) ([MSDN Reference](https://msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx)) – Ivan García Topete Apr 27 '18 at 15:07