Make a string operation using for loop to string length is costly on performance bases compare to convert it to character array and make string operation on that array
static void Main(string[] args)
{
Stopwatch sp = new Stopwatch();
sp.Start();
string output = string.Empty;
string myStr = "http://kirtimdarji.blogspot.com";
output = Program.ArrCapitalizeVowels(myStr);
Console.Write(string.Format("Time Elaspeds:{0} output:{1}\n", sp.Elapsed, output));
sp.Reset();
sp.Start();
output = Program.CapitalizeVowels(myStr);
Console.Write(string.Format("Time Elaspeds:{0} output:{1}\n", sp.Elapsed, output));
Console.ReadKey();
}
private static string CapitalizeVowels(string input)
{
if (string.IsNullOrEmpty(input)) //since a string is a class object, it could be null
return string.Empty;
else
{
string output = string.Empty;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == 'a' || input[i] == 'e' ||
input[i] == 'i' || input[i] == 'o' ||
input[i] == 'u')
output += input[i].ToString().ToUpper(); //Vowel
else
output += input[i].ToString().ToLower(); //Not vowel
}
return output;
}
}
public static string ArrCapitalizeVowels(string input)
{
if (string.IsNullOrEmpty(input)) //since a string is a class object, it could be null
return string.Empty;
else
{
char[] charArray = input.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (charArray[i] == 'a' || charArray[i] == 'e' ||
charArray[i] == 'i' || charArray[i] == 'o' ||
charArray[i] == 'u')
charArray[i] = char.ToUpper(charArray[i]); //Vowel
else
charArray[i] = char.ToLower(charArray[i]); //Not vowel
}
return new string(charArray);
}
}
Output :ArrCapitalizeVowels Method
Time Elaspeds:00:00:00.0007757 output:http://kIrtImdArjI.blOgspOt.cOm
CapitalizeVowels Method
Time Elaspeds:00:00:00.0008297 output:http://kIrtImdArjI.blOgspOt.cOm
Thank You for reading stay turned for more!!
Kirti Darji