如何在c#中仅删除部分字符串 [英] How do I remove only part of a string in c#

查看:73
本文介绍了如何在c#中仅删除部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了很多方法来摆脱字符串的一部分,例如让我们取字符串s =ABCDEFG * HI,我想只删除*符号。



我在StackOverflow中看到了很多这样做的例子,但他们提供的解决方案只支持删除CHAR的选定索引并转发...



  string  s =   ABDCEFG * HI; 
s = s.Remove(s.LastIndexOf(' *'));
// 输出应该是没有*符号的ABCDEFGHI,但实际上,结果是是ABCDEFG





我也尝试使用s.IndexOf而不是s.LastIndexOf,但仍然没有区别...

非常感谢任何帮助,谢谢

解决方案

试试这个:



  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 StackOverflow 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,'*');


这篇关于如何在c#中仅删除部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆