Break string into words.
I’ve written a method which will format any given string into a more readable phrase.
This method can be quite useful if you’re generating your code or building your API based on an outer settings like a config file, DB, Reflection etc.
Code:
/// <summary>
/// Format the string so it will be more readable.
/// </summary>
/// <param name=”field”>The field to format</param>
/// <remarks>
/// Written by Oren Ellenbogen (23/01/2006) – parsing string AI for idiots ;)
/// </remarks>
/// <returns>Formatted field name</returns>
public string FormatField(string field)
{
StringBuilder formattedField = new StringBuilder(field.Length * 2);
for (int i = 0; i < field.Length; i++)
{
if (i == 0)
formattedField.Append(field[i].ToString().ToUpper());
else
{
if (field[i].ToString().ToLower() != field[i].ToString())
{
// The current char is in upper case format.
if (i < (field.Length – 1))
{
// Move forward & backward on the string and see if the previous/next char is in lower case.
// If so – put a space to separate the words.
if (field[i + 1].ToString().ToLower() == field[i + 1].ToString() ||
field[i – 1].ToString().ToLower() == field[i – 1].ToString())
{
formattedField.Append(” “);
}
}
}
formattedField.Append(field[i]);
}
}
return formattedField.ToString();
}
Usage:
// Print: Total Mails
Console.WriteLine(FormatField(“totalMails”));
// Print: User ID
Console.WriteLine(FormatField(“UserID”));