-1

I used replace keyword to replace string or char, and i can replace successfully here is my code

string keywoord = "Emerika";
var result = keywoord.Replace(keywoord[0], 'A');

the result : Amerika

but i get strange behaviour when replace thing and the next thing is same

 string keywoord = "xxxxx";
    var result = keywoord.Replace(keywoord[0], 'A');

I will get result : AAAAA

It should return Axxxx

string keywoord = "aaakaaa";
      var result = keywoord.Replace(keywoord[0], 'z');

I will get result : zzzkzzz

It should return zaakaaa

so what happened with this, i just need to replace one thing not multiple thing, any error or do u have another solution?

13
  • 2
    Why do you expect that Replace('x', 'A'); will replace only one occurrence? Commented Nov 3, 2019 at 18:01
  • keyword[0] = a So you're replacing all a with z Commented Nov 3, 2019 at 18:01
  • no keyword[0] mean that i replace only first Commented Nov 3, 2019 at 18:03
  • @Progman i think it occure one because it's not looping Commented Nov 3, 2019 at 18:04
  • @NurMahin, The first parameter you're passing to Replace is the character you want to search and replace, not the position in the string that you want to replace. Commented Nov 3, 2019 at 18:05

2 Answers 2

0

If you want to replace the first n apparitions you can use Regex.

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

//result HellFoo World

  • "o" is the text witch you want to replace with
  • "Hello World" is the text in which you want to make changes
  • "Foo" is the replacement
  • 1(the third parameter) is the number of replacements(the first n occurrences to replace)
Sign up to request clarification or add additional context in comments.

Comments

0

A couple of things to understand -

  1. Some Replace implementations, for example in JavaScript, only replace the first occurrence of the searched string. The C# implementations do not, it replaces ANY occurrence, so if you replace every "x" in "xxxx" with an "A", you get "AAAA".

  2. The first parameter you pass to Replace is the value that you want to look for, and the second parameter is the value you want to replace it with.

See these examples -

"Emerika".Replace('E', 'A'); // "America"
"Emerika".Replace('k', 'A'); // "EmeriAa"
"Emerika".Replace('x', 'A'); // "Emerika", because there is no 'x' to replace
"xxxx".Replace('g', 'a'); // "xxxx", becuase there is no 'g' to replace
"xxxx".Replace('x', 'A'); // "AAAA", becuase every 'x' was replaced with an 'A'

var str = "Emerika";
str.Replace(str[0], 'A'); // "America", but just because the value of str[0] is equal to 'E', so this is just like out first example.

Here's a link to the MSDN page for String.Replace with some more explanations

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.