Menu
Coddy logo textTech

Substrings

Lesson 5 of 14 in Coddy's Strings and Arrays in C# course.

Let's learn some more string methods related to substrings!

To get a substring (portion of a string) of some string in C# use the method Substring() with the start and end index(s),

string word = "howareyou";
string sub = word.Substring(3, 6);

In the above example, sub will hold the string "are" because the 3rd index is the character 'a' and the 6th index is the character 'y' but the end index is excluded.

Remember! indexes are starting from 0

Another important method is IndexOf() which returns the position of the first found occurrence of a specified character(s) in a string,

string sentence = "how$are$you";
int i = word.IndexOf("$"); // Returns 3
string sub = sentence.Substring(0, i);

In the above example, we find the position of the first occurrence of "$" in sentence, in the end sub will hold "how".

Note! If you use Substring() with just one argument, for example s.Substring(2), it will return the substring from the 2nd index to the end!

The last method we will learn here is Contains() which checks whether a string contains a sequence of characters,

string sentence = "how$are$you";
bool res1 = sentence.Contains("$"); // Returns false
bool res2 = sentence.Contains('); // Returns true
bool res2 = sentence.Contains("are"); // Returns true
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Write a function named getFirstPart that takes a string (s) as an argument and returns its first part.

String's first part is the substring before the first occurrence of ",", if there is no "," in s the first part is "NONE"

Try it yourself

using System;

class GetFirstPart {
    public static string getFirstPart(string a1) {
        // Write code here
    }
}

All lessons in Strings and Arrays in C#