开发者

How to remove a string from a string

I am adding a string (a) to another string (b) before I store it in DB, wh开发者_Python百科en I retrieve the value from DB, I want to remove the string(b) from string (a). string (b) is a constant. How can I do it

string a= "text1";
string b="text2";
string c = a+b;

I want to remove b from c after I retrive it from db


c = c.Replace(b, "");

Would be a simple way to do so.


Rather than do any of that, create a computed column in the DB that has the extra text.

Less storage; less code.


Try String.Replace - MSDN documentation here.


As @SvenS has pointed in @Khaled Nassar answer, using String.Replace won't work "as is" in your situation.

One acceptable solution may @Mitch's one, but if you don't have that access to modify your database, maybe there's another solution in pure C#:

int indexOfB = c.LastIndexOf(b);
string cWithoutB = c;

if(indexOfB >= 0)
{
     c.Substring(0, indexOfB);
}

This prevents replacing more than once the same string as b, because who knows if some user save the same text as b and logic shouldn't be removing it if it's not the one predefined by your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜