ASPCode.net logo
  • Home 
  • Blogs 
  • Tags 
Blog
  1. Home
  2. Articles
  3. C# Basics - String manipulation

C# Basics - String manipulation

Posted on June 25, 2024  (Last modified on October 11, 2024) • 2 min read • 351 words
C#
 
C#
 
Share via
ASPCode.net
Link copied to clipboard

Video is in Swedish

Title: C# Basics - String Manipulation

Introduction: In this article, we will explore the basics of string manipulation in C#. Strings are an essential data type in programming and are used to store text or characters. In C#, strings can be manipulated using various methods and functions.

Step 1: Declaring a string To start manipulating strings in C#, you first need to declare a string variable. Here’s how you do it:

string myString = "Hello, World!";

Step 2: Accessing characters Once you have declared a string, you can access individual characters using the index operator ([]). The index starts at 0 and goes up to myString.Length - 1, where Length is a property that returns the number of characters in the string.

char firstChar = myString[0]; // 'H'
char lastChar = myString[myString.Length - 1]; // '!'

Step 3: Concatenating strings You can concatenate (join) two or more strings using the + operator. This is useful when you want to combine multiple pieces of text into a single string.

string greeting = "Hello, ";
string name = "World!";
string message = greeting + name; // "Hello, World!"

Step 4: Substrings and slicing To extract a portion of a string, you can use the Substring method. This method takes two parameters: the starting index (inclusive) and the length of the substring.

string firstHalf = myString.Substring(0, myString.Length / 2); // "Hello"

Step 5: String manipulation functions C# provides several built-in methods for manipulating strings. Some common ones are:

  • ToUpper() and ToLower(): Converts all characters in the string to uppercase or lowercase.
string upperCase = myString.ToUpper(); // "HELLO, WORLD!"
  • Trim(): Removes leading and trailing whitespace from the string.
string trimmed = myString.Trim(); // "Hello, World!"
  • Replace(): Replaces all occurrences of a specified character or substring with another character or substring.
string replaced = myString.Replace("o", "x"); // "Hxllo, Wrld!"

Conclusion: In this article, we covered the basics of string manipulation in C#. By declaring strings, accessing characters, concatenating strings, extracting substrings, and using built-in functions, you can perform a wide range of text operations. Understanding these concepts is essential for working with text data in any programming language.

Video  

Swedish

 C# Basics - Input & Casting
C# Basics - Conditional Statements 
Follow me

I code in Java, C#, Golang, SQL and more

     
© 2024 Systementor AB
ASPCode.net
Code copied to clipboard