C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Method: The method converts the string to a char array using ToCharArray, which you can modify in-place. It uses the static Array.Sort method.
And: The final line in the method creates a new string from the char array it modified, and returns it.
Char ArrayArray.SortChar array: With char arrays, you can change a character in a char array all by itself, which you cannot do with a string. This is much faster.
ToCharArrayC# program that alphabetizes strings
using System;
class Program
{
static void Main()
{
Console.WriteLine(StringTools.Alphabetize("sam"));
Console.WriteLine(StringTools.Alphabetize("spot"));
Console.WriteLine(StringTools.Alphabetize("cat"));
}
}
public static class StringTools
{
/// <summary>
/// Alphabetize the characters in the string.
/// </summary>
public static string Alphabetize(string s)
{
// 1.
// Convert to char array.
char[] a = s.ToCharArray();
// 2.
// Sort letters.
Array.Sort(a);
// 3.
// Return modified string.
return new string(a);
}
}
Output
ams
opst
act
Caution: This method compares the numeric values of chars, so it won't work right on uppercase letters.
CharIsAlpha: This method contains a foreach iterative statement that loops through each character in the string.
And: If it finds a character that is lower in its ordinal value than the previous character, it returns false.
Also: It returns early when it finds an incorrect (non-alphabetized) character. In this situation, no further processing is needed.
ForeachC# program that checks alphabetical strings
public static class StringTools
{
/// <summary>
/// Alphabetize string, checking to see if it is already alphabetized.
/// </summary>
public static string AlphabetizeCheck(string s)
{
if (IsAlpha(s))
{
return s;
}
else
{
// TODO: Sort and return the new string.
return "";
}
}
/// <summary>
/// See if letters in string are in numeric ascending order.
/// </summary>
public static bool IsAlpha(string s)
{
char prev = char.MinValue;
foreach (char c in s)
{
if (c < prev)
{
return false;
}
prev = c;
}
return true;
}
}