Jump to content

[C#] Format a string to proper case

- - - - -

  • Please log in to reply
2 replies to this topic

#1
PsychoCoder

PsychoCoder

    Learning Programmer

  • Members
  • PipPipPip
  • 92 posts

/// <summary>

/// method to convert a string to proper case 

/// </summary>

/// <param name="str">value we want converted</param>

/// <returns></returns>

public static string FormatProperCase(this string str)

{

    StringBuilder sb = new StringBuilder(str.Length);

    // if not value is provided throw an exception

    if (string.IsNullOrEmpty(str))

        throw new ArgumentException("A null value cannot be converted", str);


    //if the stirng is less than 2 characters return it upper case

    if (str.Length < 2)

        return str.ToUpper();


    //let's start with the first character (make upper case)

    sb.Append(str.Substring(0, 1).ToUpper());

    //now loop through the rest of the string converting where needed

    for (int i = 1; i < str.Length; i++)

    {

        if (Char.IsUpper(str[i]))

            sb.Append(" ");

        else

            sb.Append(str[i]);

    }


    //return the formatted string

    return sb.ToString();

}


Edited by PsychoCoder, 25 August 2010 - 05:16 PM.

SELECT * FROM Users WHERE Clue > 0;
ERROR: 0 results returned
Posted Image

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
It's great that you tried, but have you ever considered making it efficient? Your code is extremely inefficient, because it uses += string concatenation. You should use StringBuilder instead. It's hundreds of times faster while appending Strings.
For every string concatenation a new StringBuilder object is created, the specified String is appended and the resulting String is returned. See the problem?

#3
PsychoCoder

PsychoCoder

    Learning Programmer

  • Members
  • PipPipPip
  • 92 posts
You know I never thought of the performance implications of using concatenation over using a StringBuilder, changed it to use a StringBuilder
SELECT * FROM Users WHERE Clue > 0;
ERROR: 0 results returned
Posted Image




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users