Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

How to trim the end of a string after the first occurrence of a char C#

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
input.Substring(0, input.IndexOf('.'))

Explanation:

  1. Use 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 index 3.
  2. Use 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

int index = input.IndexOf('.');
if (index != -1)
    substring = input.Substring(0, index);

Actually, there is a lot of options to do what you want:

  1. Fast input.Substring(0, input.IndexOf('.'))
  2. Minimalistic input.Split('.')[0]
  3. For Regex lovers Regex.Match(input, @"[^.]*").Value
  4. For LINQ maniacs new string(input.TakeWhile(ch => ch != '.').ToArray())
  5. Extension methods for clean code lovers. input.SubstringUpTo('.')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...