input.Substring(0, input.IndexOf('.'))
Explanation:
- 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
.
- 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:
- Fast
input.Substring(0, input.IndexOf('.'))
- Minimalistic
input.Split('.')[0]
- For Regex lovers
Regex.Match(input, @"[^.]*").Value
- For LINQ maniacs
new string(input.TakeWhile(ch => ch != '.').ToArray())
- Extension methods for clean code lovers.
input.SubstringUpTo('.')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…