Strings in C#
Introduction
This topic will demonstrate some of the common properties and methods of the String
class:
- Property:
.Length
- Methods:
.ToUpper()
.ToLower()
.Substring(start)
and.Substring(start, length)
.Contains(string)
Strings Demo
Create a C# Console application called StringsDemo.
Steps
- Add the code comment block (replace authorname with your name, and modifieddate with the date you write this code):
- Add the comment structure inside the
static void Main(string[] args)
method:
- Start by adding the following code below the first comment line inside the
Main()
method:
Note: There is a constant declared and initialized as you do not want to change the value ofName
in this demo. Additionally, you can repalce the value ofName
with your own name. - First, you will explore the
.Length
property of a string. Add the following code below code you enetered in step 3 above:
- Next, you will explore the
.ToUpper()
method by adding the followig code:
Note: You can replace the.ToUpper()
with.ToLower()
to see the value ofName
in all lowercase letters. - In this next part, you will explore the
.Substring()
method. There are two overloads for this method. The first is extracting a portion inside the string by stating a start and a length of the portion of the string. Add the following code:
- The other overload of the
.Substring()
method just uses a starting point and will select the portion of the string from there to the end of the string. Add the following code:
- Lastly, you will explore the
.Contains()
method. This method returns a boolean (True or False) depending on whether the search string is contained in the given string. Add the following code:
-
Finally, add the
Console.ReadLine();
code line below the code entered above.The output from this demo should look like:
Note: It is important to note that the first character of a string is at position 0.