Remove text after a string occurrence

后端 未结 5 1034
温柔的废话
温柔的废话 2021-01-19 05:38

I have a string that has the following format:

string sample = \"A, ABC, 1, ACS,,\"

As you can see, there are 5 occurences of the ,

相关标签:
5条回答
  • 2021-01-19 06:11

    Use the String.Substring method

    http://msdn.microsoft.com/en-us/library/system.string.substring(v=VS.100).aspx

    0 讨论(0)
  • 2021-01-19 06:11

    Assuming that you want to return the full string if there aren't enough commas to satisfy the count

    String fx(String str, Int32 commaCount) 
        {
            if (String.IsNullOrEmpty(str)) return str;
            var i = 0;
            var strLength = str.Length;
            while ((commaCount-- > 0) && (i != -1) && (i < strLength)) i = str.IndexOf(",", i + 1);
            return (i == -1 ? str : str.Substring(i));
        }
    
    0 讨论(0)
  • 2021-01-19 06:15

    You could do something like this:

    sample.Split(',').Take(4).Aggregate((s1, s2) => s1 + "," + s2).Substring(1);
    

    This will split your string at the comma and then take only the first four parts ("A", " ABC", " 1", " ACS"), concat them to one string with Aggregate (result: ",A, ABC, 1, ACS") and return everything except the first character. Result: "A, ABC, 1, ACS".

    0 讨论(0)
  • 2021-01-19 06:29

    You could use a string.replace if it is always two commas at the end

    http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx

    0 讨论(0)
  • 2021-01-19 06:30

    If you use the GetNthIndex method from this question, you can use String.Substring:

    public int GetNthIndex(string s, char t, int n)
    {
        int count = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == t)
            {
                count++;
                if (count == n)
                {
                    return i;
                }
            }
        }
        return -1;
    }
    

    So you could do the following:

    string sample = "A, ABC, 1, ACS,,";
    int index = GetNthIndex(sample, ',', 4);
    string result = sample.Substring(0, index);
    
    0 讨论(0)
提交回复
热议问题