-4
string str="My name is abc"
string name="logan"

I want to replace 'abc' with string name in console application c#.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
suhaas
  • 3
  • 3

2 Answers2

0

You could use the String.Format-Function.

There you can replace fragments inside a String with a value you choose:

string str = "My name is {0}"; // the {n} defines the parameter-index, you can add as many parameters you want: {0}, {1}, {2}, ...
string name = "Logan"; // your input

string replace = String.Format(str, name) // multiple parameters possible

Console.WriteLine(replace);
// My Name is Logan
Me3nTaL
  • 139
  • 2
  • 11
0

Assuming you can't make changes in your string:

string str = "My name is abc";
string name = "logan";
    
int lastIndex = str.LastIndexOf(" ");
if (lastIndex > 0) {
    str = str.Substring(0, lastIndex + 1) + name;
}

Console.WriteLine (str);
briba
  • 2,857
  • 2
  • 31
  • 59