String manipulation in C#

- Posted in Coding by

Here is a method that, if passed a proper noun, such as a person's name or a street address, will return a properly formatted version of that string:

public static string ProperlyCapitalizeName(string p)
{
string sResult = string.Empty;
string sFirst = string.Empty;
string sRemaining = string.Empty;
p = p.Trim();
if(p.Length >= 2)
{
sFirst = p.Substring(0,1).ToUpper();
sRemaining = p.Substring(1,p.Length -1).ToLower();
sResult = sFirst + sRemaining;
}else{
if(p.Length < 1)
{
sResult = "";
}else{
sResult = sFirst.ToUpper();
}
}
return sResult;
}
view raw capitalizeName hosted with ❤ by GitHub

And here is an example of using method ProperlyCapitalizeName in a program:

using System;
using System.Text;
namespace Example {
class Program {
static void Main(string[] args){
string[] words = {"mr.", "bryan", "miller"};
for(int i=0; i < words.Length; i++){
Console.Write("{0} ", ProperlyCapitalizeName(words[i]));
}
}
public static string ProperlyCapitalizeName(string p)
{
string sResult = string.Empty;
string sFirst = string.Empty;
string sRemaining = string.Empty;
p = p.Trim();
if(p.Length >= 2)
{
sFirst = p.Substring(0,1).ToUpper();
sRemaining = p.Substring(1,p.Length -1).ToLower();
sResult = sFirst + sRemaining;
}else{
if(p.Length < 1)
{
sResult = "";
}else{
sResult = sFirst.ToUpper();
}
}
return sResult;
}
}
}
view raw capName.cs hosted with ❤ by GitHub