E
E
estry2019-05-30 10:59:32
C++ / C#
estry, 2019-05-30 10:59:32

How to replace elements in a C# string?

Hey!
There is a line

string s = "<div>Здесь нам нужно заменить некоторый текст, текст, текст</div>";

There are four tasks to solve:
1) Replace only the last match. For example, replace the last "text" with "TEXT"
2) Replace the first two matches. It should turn out like this: "Here we need to replace some TEXT, TEXT, text"
3) Replace matches with certain numbers. For example, replace 1 and 3 match.
4) Replace all matches
If everything is clear with 4, then with the other three it’s not very ... Please help and thank you in advance for the answers!
s = s.Replace("текст", "ТЕКСТ");

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2019-05-30
@estry

You need to find all the places where there is the right word.

string s = "<div>Здесь нам нужно заменить некоторый текст, текст, текст</div>";
var word = "текст";
var replaceTo = "ТЕКСТ";
var words = new List<int>();
int lastPos = 0;
int pos = 0;
do
{
    pos = s.IndexOf(word, lastPos);
    if (pos >= 0)
    {
        words.Add(pos);
        lastPos = pos + word.Length;
    }
}
while (pos >= 0);

And now you can do anything with them - replace at least everything, at least one at a time.
For example, replacing the first word
UPD. Instead of a loop, you can find words using a regular expression:
string s = "<div>Здесь нам нужно заменить некоторый текст, текст, текст</div>";
var word = "текст";
var replaceTo = "ТЕКСТ";
var words = new Regex(word).Matches(s).OfType<Match>().Select(match => match.Index).ToList();
var result = s.Substring(0, words[0]) + replaceTo + s.Substring(words[0] + word.Length);

A regex can take longer than a loop. But the search code is in one line!
If only whole words are needed (no need to search for "text", for example), then the search algorithm in the loop becomes more complicated (check the character before and after the found text, whether it is a space or punctuation or something else). And in the regex, you can write new Regex(@"\b" + word + @"\b").Matches(s), and the regular expression will do everything by itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question