CodeGym /Courses /C# SELF /Main methods of the string class

Main methods of the string class

C# SELF
Level 9, Lesson 3
Available

1. Intro

In real life, you’ll most often run into these string tasks:

  • Get the length of a string (and check if it’s empty).
  • Change the case of letters (make EVERYTHING UPPERCASE or all lowercase).
  • Find out if a string contains a certain word or character.
  • Replace a “bad word” with something more polite.
  • Split a string by a delimiter (“list of phone numbers separated by commas”).
  • Remove spaces at the beginning and end of a string.
  • Get a part of a string (like the first 3 letters of a last name).
  • Compare two strings — do they match if you ignore case?

And for each of these, the string class has its own method.

Table of key methods

Operation Method/Property Example
String length
Length
name.Length
First character
[0]
name[0]
Last character
[name.Length - 1]
name[name.Length - 1]
To lowercase
ToLower()
name.ToLower()
To uppercase
ToUpper()
name.ToUpper()
Check if substring exists
Contains()
name.Contains("Ivan")
Substring position
IndexOf()
name.IndexOf("a")
Extract part of string
Substring()
name.Substring(1, 3)
Compare strings
Equals(), ==
name.Equals("Petr")
Remove spaces
Trim()
name.Trim()
Split by delimiter
Split()
csv.Split(',')
Join array into string
string.Join()
string.Join("-", array)
Replace part
Replace()
text.Replace("old", "new")
Empty string?
IsNullOrEmpty()
string.IsNullOrEmpty(name)

Today we’ll go through some of these.

2. Working with a string like an array

String length: property Length

The simplest thing — find out how many characters are in a string. For this, we use the Length property. Example:

string name = "Alice";
Console.WriteLine(name.Length);  // Will print: 7
  • Length is a property (not a method), so you don’t need parentheses.
  • If the string is empty (""), the length will be 0.

Sometimes it’s useful to check the string’s length before doing something “dangerous” with it (like taking a substring).

Getting a character by index: indexer [i]

Just like with arrays: a string is an array of characters. Example:

string hello = "Hello";
char firstChar = hello[0]; 	// 'P'
char lastChar = hello[^1]; 	// 't'
Console.WriteLine(firstChar);
  • Indexing starts at zero!
  • Be careful: if you try to access a non-existent index (hello[100]), you’ll get an exception.

3. Comparing strings

String operators == and !=

In C#, these operators just compare two strings by their contents.

string word1 = "Hello";
string word2 = "Hello";
bool areEqual = word1 == word2; // true

Method Equals

Unlike the == operator, the Equals method can take parameters. For example, you can compare strings ignoring case — so "Mama" == "mama" and also equals "MAMA". Example:

string pass1 = "Qwerty";
string pass2 = "qwerty";

// standard comparison with case sensitivity
bool isSame = pass1.Equals(pass2); // false

// comparison ignoring case
bool ignoreCase = pass1.Equals(pass2, StringComparison.OrdinalIgnoreCase); // true

4. Changing case

To change a string to upper (or lower) case, the string class has 2 special methods: ToLower() and ToUpper().

Want your user to see your message in “IMPORTANT!” style? Or maybe you need to bring all names to lowercase for comparison? Easy:

string text = "I am not afraid of the gray wolf!";
Console.WriteLine(text.ToUpper()); // MNE NE STRASHEN SERYY VOLK!
Console.WriteLine(text.ToLower()); // mne ne strashen seryy volk!
  • Notice: the original string doesn’t change!
  • You can use this to check if strings match, ignoring case.

5. Removing extra spaces

What if the user accidentally (or on purpose, who knows) added spaces before and after the name? Trim to the rescue! It comes in three flavors:

  • Trim — removes all spaces at the start and end of the string;
  • TrimStart — removes spaces at the start of the string;
  • TrimEnd — removes spaces at the end of the string.
string raw = "   Bob   ";
string cleaned = raw.Trim(); 		// "Bob"
Console.WriteLine($"[{cleaned}]");

6. Getting a substring: Substring

Sometimes you just need to grab a part of a string.

string word = "Hello";
string part = word.Substring(2);      // "ivet"
string part2 = word.Substring(2, 3);  // "ive"
  • Substring(startIndex) — from character startIndex to the end.
  • Substring(startIndex, length) — starting at startIndex, take as many characters as length.

Heads up: if you go out of bounds or length < 0, you’ll get an exception!

7. Checking if a string is empty

Before using a string (like in interpolation), you should check that it’s not null and not empty, otherwise you might get an error or something weird.

a) Check for null using == operator

string s = null;
if (s == null)
    Console.WriteLine("String is null");

Downside: doesn’t catch empty string ("").

b) Check with string.IsNullOrEmpty()

Checks for both null and empty string:

string s = "";
if (string.IsNullOrEmpty(s))
    Console.WriteLine("String is empty or null");

c) Check with string.IsNullOrWhiteSpace()

Also takes into account strings that are just spaces, tabs, and other “invisible” characters:

string s = "     ";
if (string.IsNullOrWhiteSpace(s))
    Console.WriteLine("String is empty, null, or just spaces");

8. Typical mistakes when working with string methods

  • The most common — forgetting that strings are immutable (can’t be changed), like we already discussed above.
  • Another popular goof — forgetting about case sensitivity when searching and comparing.

For example, if a user enters the name "Andrew", but your list already has "Andrey", then just using Contains or == might not work unless you bring both strings to the same case or use the right overload of the method.

Also, be careful with methods that return indexes. Indexes start at zero, and if you get -1, it means nothing was found, not “index 0”.

2
Task
C# SELF, level 9, lesson 3
Locked
Counting the length of a string and its first and last characters
Counting the length of a string and its first and last characters
2
Task
C# SELF, level 9, lesson 3
Locked
Removing Spaces and Changing Case
Removing Spaces and Changing Case
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION