Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

[C#] Format a string to proper case

form string

  • Please log in to reply
2 replies to this topic

#1 PsychoCoder

PsychoCoder

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 24 August 2010 - 01:23 PM


/// <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.

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

#2 Sinipull

Sinipull

    CC Addict

  • Validating
  • PipPipPipPipPip
  • 384 posts

Posted 25 August 2010 - 04:54 PM

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?
  • 0

#3 PsychoCoder

PsychoCoder

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 25 August 2010 - 05:16 PM

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





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download