This post is about how to convert your input string into TITLE case in C#.
First , let me tell you what is title case
:
When writing a name or a title, it is a common
convention to only use capital letters to start the principal words. This is
called Title Case. When using Title Case, do not use capital letters
for prepositions, articles or conjunctions unless one
is the first word.
Examples:
Examples:
- Snow
White and the Seven Dwarfs.
- Newcastle
upon Tyne / Brighton on Sea .
- The
DiMaggio Line .
- The
Last of the Mohicans .
You can convert your input string either in C# code or in SQL function (scalar function) :
Convert to Title case in C# :
public static String TitleCaseString(String
s)
{
if (s == null) return s;
String[] words = s.Split('
');
for (int i = 0; i
< words.Length; i++)
{
if (words[i].Length == 0) continue;
Char firstChar = Char.ToUpper(words[i][0]);
String rest = "";
if (words[i].Length > 1)
{
rest = words[i].Substring(1).ToLower();
}
words[i] = firstChar + rest;
}
return
String.Join("
", words);
}
Convert to Title case in SQL Server function :
CREATE FUNCTION udf_TitleCase (@InputString VARCHAR(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Index
INT
DECLARE @Char CHAR(1)
DECLARE
@OutputString VARCHAR(255)
SET
@OutputString = LOWER(@InputString)
SET @Index = 2
SET
@OutputString =
STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))
WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(')
IF @Index + 1 <= LEN(@InputString)
BEGIN
IF @Char != ''''
OR
UPPER(SUBSTRING(@InputString, @Index
+ 1, 1)) != 'S'
SET
@OutputString =
STUFF(@OutputString,
@Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index
+ 1, 1)))
END
SET @Index = @Index + 1
END
RETURN ISNULL(@OutputString,'')
END
Hope this will help!!
Regards,
Nitin Sharma