Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
I have tried a lot of ways to get rid off a part of a string, for example lets take string s = "ABCDEFG*HI" and I wanted to remove the * symbol ONLY.

I have seen a lot of examples in StackOverflow in doing such thing but the solution they provided only supports removing the selected index of a CHAR and forward...

C#
string s = "ABDCEFG*HI";
s = s.Remove( s.LastIndexOf('*') );
//The output was supposed to be ABCDEFGHI without the * symbol, but in reality, it turns out to be ABCDEFG


I also tried using s.IndexOf instead of s.LastIndexOf, but still no difference...
Any help would be much appreciated, thank you
Posted
Comments
Sergey Alexandrovich Kryukov 7-Jul-14 15:19pm    
What's wrong with just reading original MDSN help page in System.String? It will tell you everything.
—SA

Try this:

C#
string s = "ABDCEFG*HI";
s = s.Replace("*HI", "HI");


Surely you can use Remove as well, take a look: http://msdn.microsoft.com/de-de/library/d8d7z2kk%28v=vs.110%29.aspx[^]

C#
public string Remove(
    int startIndex,
    int count
)


In your case it would be something like this (not tested):

C#
string s = "ABDCEFG*HI";
int nIndex = s.LastIndexOf('*');
if (nIndex > 0)
   s = s.Remove( nIndex, nIndex+1 );
 
Share this answer
 
v3
Comments
[no name] 7-Jul-14 14:31pm    
I tried your first code and it works like a charm, thanks :)
Leo Chapiro 7-Jul-14 14:35pm    
You are welcome! :)
C#
string RemoveCharacter(string source, char c)
  {
      return source.Replace(c.ToString(),"");
  }


For example to remove all the character '*' in "ABCDEFGH*IJK*LMN*PQRST*UVWXYZ**"

C#
string s="ABCDEFGH*IJK*LMN*PQRST*UVWXYZ**";
s=RemoveCharacter(s,'*');
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900