Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Regex – Add a . after every letter in a string

I am trying to add a . (a dot) after every letter in a string via means of a regex but I am struggling a little.

What I have tried so far:

public string convert(string s)
{

    s =  Regex.Replace(s, ".{1}", "$0.");

    return s;
}

The intput string contains only letters, each seperated by a space except for the last one.
Eg, the input could be "R B" or "A S"
If I use my above code the string becomes "R. .B." or "A. .S" .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to remove the . before each character.
The output string needs to become "R. B." or "A. S." .
How would I go about removing a . that appears before each letter? (i think it adds the extra . because of the space). Also, the string can be longer or shorter, 2 letters isnt a fixed number.

Thanks in advance.

>Solution :

Try matching on [A-Za-z], which means any single letter:

public string convert(string s)
{
    s =  Regex.Replace(s, "[A-Za-z]", "$0.");

    return s;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading