csharp-metodos-string

Common String Methods in C#

  • 3 min

Now that we know what a string is, let’s see how to work with them, using some of the common methods.

Remember that strings are immutable. That is, none of these methods modifies the original string, they all return a new one.

Access and Length

We can access each character individually as if it were an Array (read-only) using brackets [] and know its length with .Length.

string nombre = "Luis";
char letra = nombre[0]; // 'L'
int longitud = nombre.Length; // 4
Copied!

Extracting Parts (Slicing)

The Classic Way: Substring

For years we have used Substring(start, length).

string texto = "Hola Mundo";
string mundo = texto.Substring(5, 5); // From index 5, take 5 characters -> "Mundo"
Copied!

The Modern Way: Ranges (..)

Since C# 8, we have a much more powerful and expressive syntax with indices and ranges.

  • ^1 means “the first one starting from the end”.
  • [start..end] defines a range.
string archivo = "documento.pdf";

string nombre = archivo[0..^4]; // From 0 to the 4th from the end -> "documento"
string extension = archivo[^3..]; // The last 3 -> "pdf"
Copied!

To find “needles in the haystack”.

  • Contains("text"): Returns true/false.
  • **StartsWith("x") / EndsWith("x")**: Checks beginning or end.
  • IndexOf("x"): Returns the position (index) where it first appears. If it doesn’t exist, returns -1.
string frase = "El perro de San Roque";
int pos = frase.IndexOf("San"); // Returns 12
Copied!

All these methods have overloads that accept StringComparison. It’s good practice to use StringComparison.OrdinalIgnoreCase if we want to ignore case efficiently.

Manipulation and Cleaning

Trimming Spaces (Trim)

Essential when reading user input to remove extra spaces at the beginning and end.

string sucio = "   usuario   ";
string limpio = sucio.Trim(); // "usuario"
Copied!

Replace

Changes all occurrences of one text for another.

string texto = "Hola mundo, hola todos";
string nuevo = texto.Replace("Hola", "Adiós", StringComparison.OrdinalIgnoreCase);
// "Adiós mundo, Adiós todos"
Copied!

Uppercase and Lowercase

ToUpper() and ToLower(). Be careful, as in some languages (like Turkish) this has special behaviors. Use ToLowerInvariant() for internal logic.

Splitting and Joining (Split and Join)

Two of the most useful methods for processing data (like CSVs).

// SPLIT: From String to Array
string csv = "Manzana,Pera,Plátano";
string[] frutas = csv.Split(','); 

// JOIN: From Array to String
string[] palabras = { "Hola", "que", "tal" };
string frase = string.Join(" ", palabras); // "Hola que tal"
Copied!

Advanced Formatting

Although interpolation $ is king, the classic String.Format method is still useful, especially when the format comes from a database or external configuration.

decimal precio = 12.5m;

// Currency (C)
Console.WriteLine($"{precio:C2}"); // 12,50 € (According to local culture)

// Numbers with leading zeros (PadLeft/PadRight)
int numero = 5;
Console.WriteLine(numero.ToString("D3")); // "005"
Copied!