0

I want to dynamically replace an exact sub string from a string. For ex I want to replace "dis.[Test Table]" to "dbo.[Test Table]" in the following string:

SELECT Name FROM dis.[Test Table].

Note that I it could be any text and any sub string. It will replace only exactly matched sub string as many times as it will occur.

Sabith
  • 1,628
  • 2
  • 20
  • 38
R.Azmi
  • 1
  • 2

1 Answers1

0

use String.Replace() Method

fullString = fullString.Replace("oldSubString", "newSubString");

Just to elaborate further, your example can be written as:

var newString = "SELECT Name FROM dis.[Test Table]".Replace("dis.[Test Table]","dbo.[Test Table]");

// newString will become "SELECT Name FROM dbo.[Test Table]" 

More details are here

as-if-i-code
  • 2,103
  • 1
  • 10
  • 19
  • Can't use the built in .Replace function. Because that would also replace dis.[Test Table1] which is not the exact match. Even tried Regex Replace. But that didn't worked either. – R.Azmi Feb 16 '20 at 10:04
  • I would recommend `fullString = fullString.Replace("oldSubString", "newSubString");` because it actually doesn't replace the string, but returns a new one. – Jeroen van Langen Feb 16 '20 at 10:05
  • @R.Azmi Replace() will work with exact match, It will not replace **dis.[Test Table1]** Have a look here at working example https://dotnetfiddle.net/K5bqYK – as-if-i-code Feb 16 '20 at 10:13
  • Thank you @JeroenvanLangen. That's true. Answer edited (Y). – as-if-i-code Feb 16 '20 at 10:26