Tobia Zambon
Tobia Zambon

Reputation: 7639

remove chars in string except last

I'm tring to remove the char '.' from a string except the last occurrence; for example the string

12.34.56.78

should became

123456.78

I'm using this loop:

while (value != null && value.Count(c => c == '.') > 1)
 {
   value = value.Substring(0, value.IndexOf('.')) + value.Substring(value.IndexOf('.') + 1);
 }

I wonder if there is a cleaner way (maybe using linq?) to do this whitout an explicit loop?

(I know there is a very similar question but is about perl and things are quite different)

Upvotes: 3

Views: 3058

Answers (6)

urlreader
urlreader

Reputation: 6615

you do not have to use loop:

    //string val = "12345678";
    string val = "12.34.56.78";
    string ret = val;
    int index = val.LastIndexOf(".");
    if (index >= 0)
    {
        ret = val.Substring(0, index).Replace(".", "") + val.Substring(index);
    }
    Debug.WriteLine(ret);

Upvotes: 0

wageoghe
wageoghe

Reputation: 27618

Something like this should do the trick. Whether it is "good" or not is another matter. Note also that there is no error checking. Might want to check for null or empty string and that the string has at least one "." in it.

string numbers = "12.34.56.78";
var parts = String.Split(new char [] {'.'});
string newNumbers = String.Join("",parts.Take(parts.Length-1)
                                        .Concat(".")
                                        .Concat(parts.Last());

I don't claim that this would have great performance characteristics for long strings, but it does use Linq ;-)

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460340

Perhaps a mixture of string methods and Linq:

string str = "12.34.56.78";
Char replaceChar = '.';
int lastIndex = str.LastIndexOf(replaceChar);
if (lastIndex != -1)
{
    IEnumerable<Char> chars = str
        .Where((c, i) => c != replaceChar || i == lastIndex);
    str = new string(chars.ToArray());
}

Demo

Upvotes: 6

Rawling
Rawling

Reputation: 50204

int lastIndex = value.LastIndexOf('.');
if (lastIndex > 0)
{
    value = value.Substring(0, lastIndex).Replace(".", "")
        + value.Substring(lastIndex);
}

Upvotes: 5

LukeHennerley
LukeHennerley

Reputation: 6444

  var splitResult = v.Split(new char[] { '.' }).ToList();
  var lastSplit = splitResult.Last();
  splitResult.RemoveAt(splitResult.Count - 1);
  var output = string.Join("", splitResult) + "." + lastSplit;

I would do it that way. The neatest way isn't always the shortest way.

Upvotes: 1

phaazon
phaazon

Reputation: 2002

I would do that way:

  1. search for the last '.' ;
  2. substring [0 .. indexOfLastDot] ;
  3. remove in place any '.' of the substring
  4. concatenate the substring with the rest of the original string, [indexOfLastDot .. remaining]

OR

  1. search for the last '.'
  2. for each enumerated char of the string
  3. if it’s a '.' and i ≠ indexOfLastDot, remove it

Upvotes: 1

Related Questions