How to trim the end of a string after the first oc

2019-09-22 09:24发布

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.

标签: c#
4条回答
Melony?
2楼-- · 2019-09-22 10:06

(I'm posting this just for completeness - Sergey's answer seems to be correct and simplest.)

(1) A Linq approach:

s = new string(s.TakeWhile(c => c != '.').ToArray());

(2) Same as Sergey's answer, but using a Left() string extension:

string s = "143.122.124.123";
s = s.Left(s.IndexOf('.'));

Should really do error checking though:

string s = "143.122.124.123";
int n = s.IndexOf('.');

if (n >= 0)
    s = s.Left(n);

Note: The Left() method is actually an extension method, so really it's just the same as Sergey's answer:

public static class StringExt
{
    public static string Left(this string self, int count)
    {
        string result = self.Length <= count 
            ? self 
            : self.Substring(0, count);

        return result;
    }
}
查看更多
等我变得足够好
3楼-- · 2019-09-22 10:08

And now we got nuts and insist on using .LastIndexOf():

string input = "143.122.124.123";
string rev = new string(input.Reverse().ToArray());
string output = new string(rev.Substring(rev.LastIndexOf('.') + 1).Reverse().ToArray());
查看更多
对你真心纯属浪费
4楼-- · 2019-09-22 10:17
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('.')
查看更多
放我归山
5楼-- · 2019-09-22 10:22
string input = "143.122.124.123";
string output = input.Split('.')[0];

This will return the entire string if the Split character isn't found.

查看更多
登录 后发表回答