开发者

Ensure a whitespace exists after any occurance of a specific char in a string

if anyone can help me with this one...

I have a string named text. I need to ensure that after every occurrence of a specific character " there is a whitespace. If there is not a whitespace, then I need to insert one.

I am not sure on the best approach to accompl开发者_如何转开发ish this in c#, I think regular expressions may be the way to go, but I do not have enough knowledge about regular expressions to do this...

If anyone can help it would be appreciated.


// rule: all 'a's must be followed by space.
// 'a's 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

The regular expression a(?!\s) searches for 'a' that is not followed by a whitespace. The lambda expression x=>x + " " tells the replace function to replace any occurence of 'a' without a following whitespace for 'a' with a whitespace


So, assuming you have your string:

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

I assume here to put a space after each comma that has no whitespace after it. Adapt as you like.

You can use a regular expression replace:

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

This regular expression just searches for a comma that is not followed by any whitespace (space, tab, etc.) and replaces it by the same comma and a single space.

We can do a little better, still:

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

which leaves the comma intact and only replaces the empty space between a comma and a following non-whitespace character by a single space. Essentially it just inserts the new space, if needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜