Make sure that a space exists after any occurrence of a specific char in a string

if anyone can help me with this ...

I have a line called text. I need to make sure that after each occurrence of a certain character “there is a space. If there is no space, then I need to insert it.

I'm not sure of the best approach to doing this in C #, I think regular expressions can be a way, but I don't have enough knowledge about regular expressions for this ...

If anyone can help, this will be appreciated.

+3
source share
2 answers
// rule: all 'a must be followed by space.
// 'a that are already followed by space must
// remain the same.
String text = "banana is a fruit";
text = Regex.Replace(text, @"a(?!\s)", x=>x + " ");
// at this point, text contains: ba na na is a fruit

a (?!\s) "a", . x = > x + "" replace "a" "a"

+8

, :

string text = "12345,123523, 512,5,23, 18";

, , . , .

replace:

Regex.Replace(text, ",(?!\s)", ", ");

, (, ..) .

, :

Regex.Replace(text, "(?<=,)(?!\s)", " ");

. , , .

+1

Source: https://habr.com/ru/post/1727854/


All Articles