1

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

4 Answers 4

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

Would be a simple way to do so.

Sign up to request clarification or add additional context in comments.

1 Comment

May lead to problems if a can contain b before appending b.
4

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

Less storage; less code.

1 Comment

Or if he's using a an ORM, maybe some kind of "on adding" and "on updating" field interceptor.
2

Try String.Replace - MSDN documentation here.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.