I want to trim the end of a string after the first occurence of a given character, in this case '.'
This character appears multiple times in the string.
- Input: 143.122.124.123
- Output: 143
I can find multiple questions similar to this alhtough they all use LastIndexOf()
; where as this requires the first occurence and remove the rest of the string.
(I'm posting this just for completeness - Sergey's answer seems to be correct and simplest.)
(1) A Linq approach:
(2) Same as Sergey's answer, but using a
Left()
string extension:Should really do error checking though:
Note: The
Left()
method is actually an extension method, so really it's just the same as Sergey's answer:And now we got nuts and insist on using
.LastIndexOf()
:Explanation:
String.IndexOf(char)
to get zero-based index of first char occurrence in string. E.g. for your input it will be the fourth character with index3
.String.Substring(startIndex,length)
to get the substring from the beginning of the string. Use the index of char as the length of the substring, because the index is zero-based.Note:
pros of this solution (comparing to using
Split
) is that it will not create arrays in memory and will not traverse all string searching for split character and extracting substrings.cons of this solution is that string must contain at least one character you are looking for (thanks to Ivan Chepikov for mentioning it). Safe alternative will look like
Actually, there is a lot of options to do what you want:
input.Substring(0, input.IndexOf('.'))
input.Split('.')[0]
Regex.Match(input, @"[^\.]*").Value
new string(input.TakeWhile(ch => ch != '.').ToArray())
input.SubstringUpTo('.')
This will return the entire string if the
Split
character isn't found.