0
0
C Sharp (C#)programming~5 mins

Common string methods in C Sharp (C#)

Choose your learning style9 modes available
Introduction

String methods help you work with text easily. They let you change, check, or find parts of words or sentences.

When you want to change all letters to uppercase or lowercase.
When you need to find if a word contains a certain letter or phrase.
When you want to cut out a part of a sentence.
When you want to join words together or split a sentence into words.
When you want to remove spaces at the start or end of a sentence.
Syntax
C Sharp (C#)
string.MethodName(arguments);
Replace MethodName with the name of the string method you want to use.
Most string methods return a new string or a value; they do not change the original string.
Examples
This changes all letters in text to uppercase and saves it in upper.
C Sharp (C#)
string text = "hello";
string upper = text.ToUpper();
This checks if text contains the word "hello" and stores true or false in hasHello.
C Sharp (C#)
string text = "hello world";
bool hasHello = text.Contains("hello");
This takes the first 5 letters from text and saves it in part.
C Sharp (C#)
string text = "hello world";
string part = text.Substring(0, 5);
This removes spaces from the start and end of text and saves the result in trimmed.
C Sharp (C#)
string text = "  hello  ";
string trimmed = text.Trim();
Sample Program

This program shows common string methods: changing case, checking content, trimming spaces, and getting a part of the string.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        string greeting = "  Hello World!  ";

        string upper = greeting.ToUpper();
        string lower = greeting.ToLower();
        bool containsWorld = greeting.Contains("World");
        string trimmed = greeting.Trim();
        string sub = greeting.Substring(2, 5);

        Console.WriteLine(upper);
        Console.WriteLine(lower);
        Console.WriteLine(containsWorld);
        Console.WriteLine(trimmed);
        Console.WriteLine(sub);
    }
}
OutputSuccess
Important Notes

Strings in C# are immutable. Methods return new strings; they do not change the original.

Use Trim() to clean spaces, Contains() to check for text, and Substring() to get parts.

Summary

String methods help you work with text easily and safely.

Common methods include ToUpper(), ToLower(), Contains(), Trim(), and Substring().

Remember, these methods return new strings and do not change the original text.