Labs ICT
⭐ Pro Login

String Methods

2 min read | C# Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Strings in C# come packed with useful methods. You can measure them, change case, chop them up, or find things inside them. Here are the most common ones.

Length

Length gives you the number of characters in a string. It's a property, not a method, so no parentheses.


using System;

class Program {
  static void Main() {
    string msg = "Hello";
    Console.WriteLine(msg.Length);
  }
}
    

ToUpper and ToLower

Convert the entire string to uppercase or lowercase. Great for case-insensitive comparisons.


using System;

class Program {
  static void Main() {
    string text = "C# is Awesome";
    Console.WriteLine(text.ToUpper());
    Console.WriteLine(text.ToLower());
  }
}
    

Substring

Extract a portion of a string. Pass the starting index and optionally the length you want.


using System;

class Program {
  static void Main() {
    string word = "Programming";
    Console.WriteLine(word.Substring(0, 7));
    Console.WriteLine(word.Substring(7));
  }
}
    

Replace, Split, Trim, IndexOf

Replace swaps all occurrences of one substring for another. Split breaks a string into an array. Trim removes whitespace from both ends. IndexOf finds the position of a substring.


using System;

class Program {
  static void Main() {
    string sentence = "  The quick brown fox  ";
    
    Console.WriteLine(sentence.Trim());
    Console.WriteLine(sentence.Replace("fox", "dog"));
    
    string[] words = sentence.Trim().Split(' ');
    foreach (var w in words) {
      Console.WriteLine(w);
    }
    
    Console.WriteLine(sentence.IndexOf("quick"));
  }
}
    

Chaining Methods

Most string methods return a new string, so you can chain them together in one line.


using System;

class Program {
  static void Main() {
    string input = "  C# Programming  ";
    string result = input.Trim().ToUpper().Replace("C#", "CSharp");
    Console.WriteLine(result);
  }
}