Some string operations
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Some string operations.
using System;
public class StrOps {
public static void Main() {
string str1 =
"When it comes to .NET programming, C# is #1.";
string str2 = string.Copy(str1);
string str3 = "C# strings are powerful.";
string strUp, strLow;
int result, idx;
Console.WriteLine("str1: " + str1);
Console.WriteLine("Length of str1: " +
str1.Length);
// create upper- and lowercase versions of str1
strLow = str1.ToLower();
strUp = str1.ToUpper();
Console.WriteLine("Lowercase version of str1:\n " +
strLow);
Console.WriteLine("Uppercase version of str1:\n " +
strUp);
Console.WriteLine();
// display str1, one char at a time.
Console.WriteLine("Display str1, one char at a time.");
for(int i=0; i < str1.Length; i++)
Console.Write(str1[i]);
Console.WriteLine("\n");
// compare strings
if(str1 == str2)
Console.WriteLine("str1 == str2");
else
Console.WriteLine("str1 != str2");
if(str1 == str3)
Console.WriteLine("str1 == str3");
else
Console.WriteLine("str1 != str3");
result = str1.CompareTo(str3);
if(result == 0)
Console.WriteLine("str1 and str3 are equal");
else if(result < 0)
Console.WriteLine("str1 is less than str3");
else
Console.WriteLine("str1 is greater than str3");
Console.WriteLine();
// assign a new string to str2
str2 = "One Two Three One";
// search string
idx = str2.IndexOf("One");
Console.WriteLine("Index of first occurrence of One: " + idx);
idx = str2.LastIndexOf("One");
Console.WriteLine("Index of last occurrence of One: " + idx);
}
}
Related examples in the same category