๐ŸŽ“ A1Learner
๐Ÿ”

C# String Methods

String methods are built-in tools that work on the text in a string. Each tool is written after the string and a dot.

Length and case

Length counts the characters in the word. ToUpper and ToLower return the word in a new case.

using System;

class Program
{
    static void Main(string[] args)
    {
        string word = "Program";
        Console.WriteLine(word.Length);
        Console.WriteLine(word.ToUpper());
        Console.WriteLine(word.ToLower());
    }
}

Finding a part

IndexOf gives the position where gram starts, counting from 0. Contains answers false here, because the word holds no letter z.

using System;

class Program
{
    static void Main(string[] args)
    {
        string word = "Program";
        Console.WriteLine(word.IndexOf("gram"));
        Console.WriteLine(word.Contains("z"));
    }
}

Cutting a part out

Substring with one number starts at that position and takes the rest. Two numbers set the start and the length.

using System;

class Program
{
    static void Main(string[] args)
    {
        string word = "Program";
        Console.WriteLine(word.Substring(3));
        Console.WriteLine(word.Substring(0, 3));
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        string email = "hana@mail.com";
        int at = email.IndexOf("@");
        Console.WriteLine(at);
        Console.WriteLine(email.Substring(0, at));
        Console.WriteLine(email.Substring(at + 1));
    }
}

Key points

  • Length is a property, and it counts the characters in a string.
  • ToUpper returns the text in capital letters.
  • ToLower returns the text in small letters.
  • IndexOf returns the position of the first match, counting from 0.
  • Contains reports true when the text holds the given part.
  • Substring returns a part of the text.

In this example, IndexOf finds the @ sign at position 4, and the first line prints 4. Substring from 0 with length 4 prints hana, the part before the sign. Substring from position 5 prints mail.com, the part after the sign.

Note

IndexOf returns -1 when the text holds no match.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does "Program".Length print?