5

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 , character. I need to remove everything after the 4th occurrence so that the final result will be:

string result = fx(sample, 4);
"A, ABC, 1, ACS"

Is it possible without a foreach? Thanks in advance.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
Raffaeu
  • 6,694
  • 13
  • 68
  • 110

5 Answers5

12

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".

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

Use the String.Substring method

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

smartcaveman
  • 41,281
  • 29
  • 127
  • 212
0

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

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

Slotty
  • 174
  • 1
  • 9
0

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));
    }
Lee Atkinson
  • 2,171
  • 3
  • 20
  • 32
0

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);
Community
  • 1
  • 1
Donut
  • 110,061
  • 20
  • 134
  • 146