locked
Split a camel case string RRS feed

  • Question

  • Does any one know how to split a camel case string into such as "casedWordHTTPWriter" into "Cased Word HTTP Writer" in C# 
    Thursday, May 14, 2009 6:07 AM

Answers

  • Thought I'd take a different spin on it just for fun.  Note:  capitalizing the first letter is a trivial post-step, and omitted from my solution.

    static class SplitCamelCaseExtension
    {
    	public static string SplitCamelCase( this string str )
    	{
    		return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" );
    	}
    }
    
    class Program
    {
    	static void Main( string[] args )
    	{
    		Console.WriteLine( "casedWordHTTPWriter".SplitCamelCase() );
    		Console.WriteLine( "nothing".SplitCamelCase() );
    		Console.WriteLine( "ABBA".SplitCamelCase() );
    		Console.WriteLine( "Computer".SplitCamelCase() );
    		Console.WriteLine( "aComputer".SplitCamelCase() );
    		Console.WriteLine( "anAppleComputer".SplitCamelCase() );
    		Console.WriteLine( "anIBM".SplitCamelCase() );
    		Console.WriteLine( "anIBMComputer".SplitCamelCase() );
    		Console.WriteLine( "AppleComputer".SplitCamelCase() );
    		Console.WriteLine( "IBMComputer".SplitCamelCase() );
    		Console.WriteLine( "One123Two789".SplitCamelCase() );
    		Console.WriteLine( "HTTPWriter".SplitCamelCase() );
    		Console.WriteLine( "HTTPWriter2".SplitCamelCase() );
    	}
    }
    
    • Marked as answer by Ryan_2000 Monday, May 18, 2009 2:54 AM
    Thursday, May 14, 2009 1:34 PM

All replies

  • you can split as string like "helloWorldHelloWorld" => "Hello World Hellow World" using the following code

    static string[] StringSplitter(String stringToSplit)
            {
                if (!String.IsNullOrEmpty(stringToSplit))
                {
                    List<String> words = new List<string>();
    
                    string temp = string.Empty;
                    
                    foreach (char ch in stringToSplit)
                    {
                        if (ch >= 'a' && ch <= 'z')
                            temp = temp + ch;
                        else
                        {
                            words.Add(temp);
                            temp = string.Empty + ch;
                        }
                    }
                    words.Add(temp);
                    return words.ToArray();
                }
                else
                    return null;
            }
            
            static void Main(string[] args)
            {
                StringSplitter("helloWorldHelloWorld");
            }



    Thanks,
    A.m.a.L
    .Net Goodies
    Remember to click "mark as answered" when you get a correct reply to your question
    Thursday, May 14, 2009 6:21 AM
  • here is the function for spliting string like "helloWorldHelloWorld" => "hello World Hello World"

    private static string StringSplitter(string stringtosplit)
            {
                string words = string.Empty;
                if (!string.IsNullOrEmpty(stringtosplit))
                {
                    foreach (char ch in stringtosplit)
                    {
                        if (char.IsLower(ch))
                        {
                            words += ch.ToString();
                        }
                        else
                        {
                            words += " " + ch.ToString();
                        }

                    }
                    return words;
                }
                else
                    return string.Empty;
            }
    Thursday, May 14, 2009 6:58 AM
  • Neither of those answers solve the original problem as stated in the ONE LINE specification. :)

    Here's some code that works for the problem specification:

    Input = "casedWordHTTPWriter"

    Output =

    "Cased"   <- Note first letter has become uppercased.
    "Word"
    "HTTP"    <- Note handling of consequtive uppercase letters.
    "Writer"

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main()
            {
                foreach (string text in (StringSplitter("casedWordHTTPWriter")))
                {
                    Console.WriteLine(text);
                }
            }
    
            static List<string> StringSplitter(string stringToSplit)
            {
                List<string> result = new List<string>();
                bool wasPreviousUppercase = false;
                StringBuilder current = new StringBuilder();
    
                foreach (char c in stringToSplit)
                {
                    if (char.IsUpper(c))
                    {
                        if (wasPreviousUppercase)
                        {
                            current.Append(c);
                        }
                        else
                        {
                            if (current.Length > 0)
                            {
                                result.Add(current.ToString());
                                current.Length = 0;
                            }
     
                            current.Append(c);
                        }
    
                        wasPreviousUppercase = true;
                    }
                    else  // lowercase
                    {
                        if (wasPreviousUppercase)
                        {
                            if (current.Length > 1)
                            {
                                char carried = current[current.Length-1];
                                --current.Length;
                                result.Add(current.ToString());
                                current.Length = 0;
                                current.Append(carried);
                            }
                        }
    
                        wasPreviousUppercase = false;
    
                        if (current.Length == 0)
                        {
                            current.Append(char.ToUpper(c));
                        }
                        else
                        {
                            current.Append(c);
                        }
                    }
                }
    
                if (current.Length > 0)
                {
                    result.Add(current.ToString());
                }
    
                return result;
            }
        }
    }
    
    Thursday, May 14, 2009 9:18 AM
  • Hi,
      Please try this.

            private static string SplitString(string stringtosplit)
            {
                string words = string.Empty;
                if (!string.IsNullOrEmpty(stringtosplit))
                {
                    char[] chars = stringtosplit.ToCharArray();
                    for (int charCount = 0; charCount < chars.Length; charCount++)
                    {
                        if (char.IsLower(chars[charCount]))
                        {
                            words += chars[charCount].ToString();
                        }
                        else
                        {
                            if ((char.IsUpper(chars[charCount - 1])) && (char.IsUpper(chars[charCount + 1])))
                            {
                                words += chars[charCount].ToString();
                            }
                            else
                            {
                                words += " " + chars[charCount].ToString();
                            }
                        }
                    }
                }
                return words;
            }

    If it is a small string use string to concatinate the charecters else use string builder. If you have Pascal casing or string ends with Uppercase charecters, you must modify the logic. It is applicable only for camel casing...
    -- Thanks Ajith R [Remember to Mark as Answer if it is Helpful.]
    Thursday, May 14, 2009 9:54 AM
  • Thought I'd take a different spin on it just for fun.  Note:  capitalizing the first letter is a trivial post-step, and omitted from my solution.

    static class SplitCamelCaseExtension
    {
    	public static string SplitCamelCase( this string str )
    	{
    		return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" );
    	}
    }
    
    class Program
    {
    	static void Main( string[] args )
    	{
    		Console.WriteLine( "casedWordHTTPWriter".SplitCamelCase() );
    		Console.WriteLine( "nothing".SplitCamelCase() );
    		Console.WriteLine( "ABBA".SplitCamelCase() );
    		Console.WriteLine( "Computer".SplitCamelCase() );
    		Console.WriteLine( "aComputer".SplitCamelCase() );
    		Console.WriteLine( "anAppleComputer".SplitCamelCase() );
    		Console.WriteLine( "anIBM".SplitCamelCase() );
    		Console.WriteLine( "anIBMComputer".SplitCamelCase() );
    		Console.WriteLine( "AppleComputer".SplitCamelCase() );
    		Console.WriteLine( "IBMComputer".SplitCamelCase() );
    		Console.WriteLine( "One123Two789".SplitCamelCase() );
    		Console.WriteLine( "HTTPWriter".SplitCamelCase() );
    		Console.WriteLine( "HTTPWriter2".SplitCamelCase() );
    	}
    }
    
    • Marked as answer by Ryan_2000 Monday, May 18, 2009 2:54 AM
    Thursday, May 14, 2009 1:34 PM
  • Okay, so everyone else has their fun.  I want some fun too.  Here's the Linq version:

    public static string SplitCamelCase(this string input)

    {

        int i = 0;

        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(string.Join(string.Empty, input

            .Select(c => new

            {

                Character = c.ToString(),

                Start = i++ == 0

                            || (Char.IsUpper(input[i - 1])

                            && (!Char.IsUpper(input[i - 2])

                            || (i < input.Length && !Char.IsUpper(input[i]))))

            })

            .Select(x => x.Start ? " " + x.Character : x.Character)

            .ToArray()))

            .Trim(); ;

        ;

    }


    David Morton - http://blog.davemorton.net/ - @davidmmorton
    • Proposed as answer by Dave Black Friday, January 14, 2011 11:36 PM
    Thursday, May 14, 2009 2:14 PM
  • I think this is the most accurate answer!

    Monday, May 18, 2009 2:55 AM