String Alternate Cases - CSharp System

CSharp examples for System:String Case

Description

String Alternate Cases

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Collections.Generic;
using System;//  w  w  w .j  a  v  a 2s  .com

public class Main{
        public static string AlternateCases(string input, bool firstIsUpper)
        {
            string ret = "";
            for (int i = 0; i < input.Length; i++)
            {
                if (firstIsUpper)
                    ret += input.Substring(i, 1).ToUpper();
                else
                    ret += input.Substring(i, 1).ToLower();

                firstIsUpper = !firstIsUpper;
            }

            return ret;
        }
        //Alternates cases between letters of a string, first letter's case stays the same
        //Hi -> Hi
        //longstring -> lOnGsTrInG
        public static string AlternateCases(string input)
        {
            if (input.Length == 0) return "";
            if (input.Length == 1) return input; //Cannot automatically alternate
            bool firstIsUpper = String.Compare(input.Substring(0, 1), input.Substring(0, 1).ToUpper(), false) != 0;
            string ret = input.Substring(0, 1);
            for (int i = 1; i < input.Length; i++)
            {
                if (firstIsUpper)
                    ret += input.Substring(i, 1).ToUpper();
                else
                    ret += input.Substring(i, 1).ToLower();

                firstIsUpper = !firstIsUpper;
            }

            return ret;
        }
}

Related Tutorials