You can work with strings within strings, or substrings, in several ways. These include searching for substrings and extracting substrings.
There are many ways to find a string within a string. The string class provides two methods that will determine if a string contains a particular substring:
The StartsWith method returns true if the string passed as the first parameter is contained at the beginning of the string being searched.
The EndsWith method returns true if the string passed as the first parameter is found at the end of an existing string.
The following example demonstrates searching for substrings.
using System;
namespace Client.Chapter_6___Strings
{
class Substrings
{
static void Main(string[] args)
{
//Creates an array of strings
string[] FootballTeams = new string[3] {
"Miami, Dolphins", "Oakland, Raiders", "Seattle, Seahawks"
};
//Iterates through each string in the array
foreach (string s in FootballTeams)
{
//Returns Awesome if the string starts with Miami
if (s.StartsWith("Miami"))
Console.WriteLine("Awesome!");
else
Console.WriteLine("Bummer Dude!");
}
}
}
}
The substring method of the string class allows you to provide a parameter that will retrieve the specified number of characters from the beginning of an existing string. There are many overloaded forms of this method that provide even more functionality.
The following example demonstrates extracting substrings.
using System;
namespace Client.Chapter_6___Strings
{
class ExtractingSubstrings
{
static void Main(string[] args)
{
string MyClasses = "Math 101 - Algebra";
//Creates a string that is made up of the first six chars of
//MyClasses
string MySubstring = MyClasses.Substring(6);
Console.WriteLine(MySubstring);
}
}
}