Tutorial: 09 - String Handling in C#
In strings, text is stored as read only and in sequential form of characters. In C#, string and String are equivalent. There are various ways by using which you can create a string in C# as shown in snippet below:
String Methods
- Compare
This method is used for comparing two strings. If both strings are equal it will return 0 and if both strings are not equal it will return -1. See following snippet
string str1 = "Hello";
string str2 = "Hellow";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine("Both are equal.");
}
else
{
Console.WriteLine("Both are not equal.");
}
- Contains
This method is used for checking whether a string or word exists in another string or not. It returns boolean true or false based on evaluation. See following snippet
string s = "This is a cat";
if (s.Contains("cat"))
{
Console.WriteLine("Cat Found.");
}
- Substring
Substring is used for creating another string from existing string. It takes one parameter which specifies the index from where you want to break the string in parts. Additionally you can specify second parameter which will be length. See following snippet
string s1 = "Visual Programming";
Console.WriteLine(s1.Substring(7));
// Output: Programming
string s2 = "Visual Programming";
Console.WriteLine(s2.Substring(7, 7));
// Output:
Program
IndexOf
IndexOf is used for locating occurrence of a character or word in a string. When found it returns the index of value. If there are more than one occurrences of a word or character, it will return the index of first occurrence. See following snippet
string s = "This is a cat";
Console.WriteLine(s.indexOf("cat"));
//Output: 10
Following are most common method used in handling of strings.
- Equals(string value)
- Insert(int startIndex, string value)
- IsNullOrEmpty(string value)
- Remove(int startIndex)
- Replace(string oldValue, string newValue)
- StartsWith(string value)
- EndsWith(string value)
- ToLower()
- ToUpper()
- Torim()
There are many more methods which we can't cover in a single topic.
For more detailed information you can visit official link of microsoft.
No comments:
Post a Comment