upd: Gives text. (Top topfase) We must find the word and replace it. Let it be necessary to replace "Top" with "bottom". Result -> Bottom topface

Looking for a substring, and then watching what stands next to it is, in my opinion, stupid. Searching with a IndexOf view ("word") is also not the case Who knows what separators will fall.

    5 answers 5

    A couple of options:

    1. Divide the text into words, given your separators. Then in the array of words find the right one.
    2. Highlight words from the text with a regular \w+ . Again, among the resulting list, find the right word.
    • In addition to finding the words, then they still need to be replaced by others. Those. from the array to drive back - a chore somehow. - prozac631
    • one
      It is worth describing the whole task at once. You can try to make a replacement with regulars. Make up a regular expression to allow separator characters before and after a word. Something like (\s*)(?<word>\w+)(\s*) . And replace the entries with Regex.Replace . - eigenein
    • one
      There are still boundaries of the word \b . - alexlz

    And with the separators? We must find the word, such as "hello." We are looking for help with IndexOf . You can use the regulars. You can LINQ method Contains which simply returns bool . Or I did not understand the question?

    UPDATE:

    If without regularities then: C # string replace to match whole words

    There is an example of code that does the search and replace words.

    • Your solution will also find part of the word "hello". - eigenein
    • Well then, only regulars, or list all the delimiters and pass to the Split method - sharok

    Once upon a time, they used this trick:

    1. We take the initial line "top topface" and add a space (in this case, in general case - word separator) on each side, we get "top topface"
    2. If you need to replace "top" with "bottom", then look for occurrences of "top" in the string and change it to "bottom"
    3. Remove spaces around the edges.

      Good day. In C # there is a function Replace ();

        You can, for example, like this, although it is a little bit rational if the big line

          string str = "Top topfase"; string[] words = str.Split(new Char[] { ' ' }); //так мы поместим в массив каждое слово указывая разделитель - пробел //ищем нужное слово и заменяем for (int i = 0; i <= words.Length - 1; i++) { if (words[i] == "Top") words[i] = "Bottom"; } //восстанавливаем слово string res =""; foreach (string s in words) res += s + " "; //вот и результат 

        But this way is better not to use. I just study C # myself

        • Better Regex.Split(str, @"\W+") - alexlz