By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,948 Members | 795 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,948 IT Pros & Developers. It's quick & easy.

string manupulation in .net, c#

100+
P: 121
hello all,
i have a string as
MyNameIsJOHN

but now i want it to be displayed as 'My Name Is JOHN'. ( space in between)

i have used
Expand|Select|Wrap|Line Numbers
  1.  System.Text.RegularExpressions.Regex.Replace("MyNameIsJOHN", "[A-Z]", " $0").Trim()
and i am getting 'My Name Is J O H N' , my problem is how should i get JOHN in one word rather than with space(s).

any idea
Feb 18 '09 #1
Share this Question
Share on Google+
3 Replies


100+
P: 179
The reason for it is your Regex expression...

"[A-Z]"

In your code this will replace any occurance of an uppercase letter with the space and the letter.

You'll probably want to check for something that starts with an upper case, and is not followed by another uppercase letter... however you may then struggle with something like : IAm...
Feb 18 '09 #2

balabaster
Expert 100+
P: 797
This should do the job:

[AI](?![A-Z]{2,})[a-z]*|[A-Z][a-z]+|[A-Z]{2,}(?=[A-Z]|$)

Replacement string is "$0[space]", where [space] should be replaced with an actual space character.

It will handle MyNameIsJOHN, IAmJOHN, WhatsUpWithJOHN etc. It also handles things like: WhatsUpWithJOHNToday, WhatsUpWithENGLANDToday, WhatsUpWithINDIAToday, FRANCERules

Note that between [AI] and [A-Z][a-z]+ that's a pipe char, not an uppercase i or lowercase L. Inside the [] is an uppercase a and i as they're the only single letter words I can think that are valid. If you want other valid single letter words, just insert the characters into that token to include them. Each match is a valid word in the string. Any words made entirely of upper case letters are treated as a single word.

This seems to handle most of the edge cases, i.e. uppercase names that contain valid single letter words. It basically defines a "word" token which can then be appended with a space. Maybe there are some odd cases where it doesn't work, but I can't think of any off the top of my head.

The only annoying thing I don't have time to figure out is how to stop it appending a space to the last word of the string...but you can resolve that using a simple trim on the resulting string. It would perhaps be more suitable in the longer term to have it ignore the last word and hence not add that final space though.
Feb 18 '09 #3

100+
P: 121
thanks balabaster for your response..
Feb 20 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.