string manupulation in .net, c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jay123
    New Member
    • Sep 2008
    • 121

    #1

    string manupulation in .net, c#

    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
    Code:
     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
  • IanWright
    New Member
    • Jan 2008
    • 179

    #2
    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...

    Comment

    • balabaster
      Recognized Expert Contributor
      • Mar 2007
      • 798

      #3
      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: WhatsUpWithJOHN Today, WhatsUpWithENGL ANDToday, WhatsUpWithINDI AToday, 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.

      Comment

      • jay123
        New Member
        • Sep 2008
        • 121

        #4
        thanks balabaster for your response..

        Comment

        Working...