How to remove a string from a string

后端 未结 4 1481
孤街浪徒
孤街浪徒 2021-01-28 07:40

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 consta

相关标签:
4条回答
  • 2021-01-28 08:13

    Try String.Replace - MSDN documentation here.

    0 讨论(0)
  • 2021-01-28 08:19

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

    Less storage; less code.

    0 讨论(0)
  • 2021-01-28 08:19

    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 讨论(0)
  • 2021-01-28 08:39
    c = c.Replace(b, "");
    

    Would be a simple way to do so.

    0 讨论(0)
提交回复
热议问题