How to find and replace every nth character occurrence using C# or regex? Conversion from Javascript to C#

Alice 71 Reputation points
2022-07-04T12:25:03.827+00:00

I need to Find and replace every 3rd character occurrence in a given string and replace it with H.
Can be done in C# or Regex or any other.

I found this Javascript code that does the same thing and would like to convert it into a C# code. Can you please assist ?

Found here

str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');  
  
let str = 'I amx nexver axt hoxme on Sxundxaxs';  
let n = 3;  
let ch = 'x';  
  
let regex = new RegExp("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch, "g");  
  
str = str.replace(regex, '$1y');  
  
console.log(str);  
//=> I amx nexver ayt hoxme on Sxundyaxs  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,938 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Jack J Jun 24,266 Reputation points Microsoft Vendor
    2022-07-05T02:27:16.897+00:00

    @Alice , Welcome to Microsoft Q&A, you could try the following link to convert the Javascript to c#.

         var ch = 'x';  
        var n = 3;  
        var str = "I amx nexver axt hoxme on Sxundxaxs";  
        var re = new Regex("((?:[^" + ch + "]*" + ch + "){" + (n - 1) + "}[^" + ch + "]*)" + ch);  
        var result = re.Replace(str, "${1}y");  
        Console.WriteLine(result);  
    

    Tested result:

    217430-image.png

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. Rijwan Ansari 741 Reputation points MVP
    2022-07-11T14:34:38.917+00:00

    HI @Alice

    You can try below code to get your desire result.

    var stringToApply = "74Mercedes1980";  
    var nth = 3;  
    var charToReplace = 'H';  
    var regex = new Regex("(\\S{" + (nth - 1) + "})\\S");  
    var outstr = regex.Replace(stringToApply, "$1" + charToReplace);  
    Console.WriteLine(outstr);  
      
    //output: 74HerHedHs1H80  
    

    https://stackoverflow.com/questions/72850434/c-sharp-how-to-find-and-replace-every-nth-character-occurrence-using-c-sharp-o

    0 comments No comments