且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在c#中仅删除部分字符串

更新时间:2023-02-21 17:49:58

试试这个:



  string  s =   ABDCEFG * HI跨度>; 
s = s.Replace( * HI HI);





当然你也可以使用Remove,看看:http://msdn.microsoft.com/de-de/library/d8d7z2kk%28v=vs.110%29.aspx [ ^ ]



  public   string 删除(
int startIndex,
int count





在你的情况下它会是这样的(未经测试):



  string  s =   ABDCEFG * HI; 
int nIndex = s.LastIndexOf(' *'跨度>);
if (nIndex > 0
s = s.Remove(nIndex,nIndex + 1);


  string  RemoveCharacter(字符串源, char  c)
{
return source.Replace(c.ToString(), );
}





例如删除ABCDEFGH * IJK * LMN *中的所有字符'*' PQRST * UVWXYZ **



  string  s =   ABCDEFGH * IJK * LMN * PQRST * UVWXYZ **; 
s = RemoveCharacter(s,' *');


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 *** in doing such thing but the solution they provided only supports removing the selected index of a CHAR and forward...

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

Try this:

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[^]

public string Remove(
    int startIndex,
    int count
)



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

string s = "ABDCEFG*HI";
int nIndex = s.LastIndexOf('*');
if (nIndex > 0)
   s = s.Remove( nIndex, nIndex+1 );


string RemoveCharacter(string source, char c)
  {
      return source.Replace(c.ToString(),"");
  }



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

string s="ABCDEFGH*IJK*LMN*PQRST*UVWXYZ**";
s=RemoveCharacter(s,'*');