Tuesday, March 8, 2016

Split string using Capital letters

I came across a question to split a string using capital letters.It was made up of names.

For Example:

s = "AaliyahAaronAarushiAbagail"

Expected Output:

Aaliyah
Aaron
Aarushi
Abagail

Below is the code

C#

using System;
using System.Text;

namespace StringSplitUsingCaps
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = "AaliyahAaronAarushiAbagail";
                string s1 = s.Substring(1, s.Length-1);
                StringBuilder sName = new StringBuilder(s.Substring(0,1));
                foreach (char c in s1.ToCharArray())
                {
                    if (!Char.IsUpper(c))
                        sName = sName.Append(c);
                    else
                    {
                        Console.WriteLine(sName);
                        sName.Clear();
                        sName.Append(c);
                    }
                }
                Console.WriteLine(sName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Done");
            Console.Read();
        }
    }

}

Output:







Python:

s = "AaliyahAaronAarushiAbagail"
name = s[:1]
s = s[1:]

for c in s:
if(c.isupper()):
print(name)
name = ""
name += c
else:
name += c

print (name)

Output:


No comments: