0% found this document useful (0 votes)
7 views1 page

Strings and StringBuilder

The document contains two C# code examples demonstrating string manipulation and the use of StringBuilder. The first example shows how to trim, split, and replace parts of a string, as well as check for null or empty strings. The second example illustrates how to build a string using StringBuilder with methods like Append and Insert.

Uploaded by

posubabu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Strings and StringBuilder

The document contains two C# code examples demonstrating string manipulation and the use of StringBuilder. The first example shows how to trim, split, and replace parts of a string, as well as check for null or empty strings. The second example illustrates how to build a string using StringBuilder with methods like Append and Insert.

Uploaded by

posubabu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

String

==============================
static void Main(string[] args)
{
string name = " Tom Hanks ";
Console.WriteLine("Name: '{0}'", name);
Console.WriteLine("Trimmed: '{0}'", name.Trim().ToUpper());
name = name.Trim(); // To remove lead/ trail spaces

var index = name.IndexOf(" ");


Console.WriteLine("Index of {0} is {1}", " ", index);
Console.WriteLine("First name: {0}", name.Substring(0, index));
Console.WriteLine("Last name: {0}", name.Substring(index + 1));

var firstName = name.Split(" ")[0];


var lastName = name.Split(" ")[1];
Console.WriteLine("First name: {0}\nLast name: {1}", firstName,
lastName);

name = name.Replace("Hanks", "Holland");


Console.WriteLine("New name: {0}", name);

// Methods to deal with null/ empty string


if (String.IsNullOrEmpty("") || string.IsNullOrEmpty(null))
{
Console.WriteLine("The string is null");
}

Console.WriteLine(string.IsNullOrEmpty(" ")); // False; not null nor


empty
Console.WriteLine(String.IsNullOrEmpty(" ".Trim())); // True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
}

StringBuilder
==========================================
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder("TCS");
sb
.Append(", Tata")
.AppendLine(" Consultancy Services")
.Insert(0, "I Work in ");
Console.WriteLine(sb.ToString());
}

You might also like