简体   繁体   中英

How to remove a string from a string

I am adding a string (a) to another string (b) before I store it in DB, when 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, "");

这将是一个简单的方法。

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

Less storage; less code.

在这里尝试String.Replace -MSDN文档。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM