C# : String Operations and Regular Expressions

Time: Column:Mobile & Frontend views:206

C# provides a rich set of string manipulation methods and support for regular expressions, making text processing relatively simple. Mastering these basic knowledge and techniques can significantly improve our programming efficiency and code quality. In C# programming, string manipulation and regular expressions are two powerful tools for handling textual data. String manipulation allows us to perform basic operations on strings, such as concatenation, substring extraction, and replacement, while regular expressions provide a powerful pattern matching mechanism to search for substrings that match a specific pattern within a string. This article will briefly introduce string operations and regular expressions in C#, along with example code.

C# : String Operations and Regular Expressions

String Operations

Strings in C# are immutable, meaning once a string object is created, its content cannot be changed. However, C# offers a variety of methods to facilitate string manipulation.

Common String Operations

  • Length: Gets the length of the string.

  • Substring(int startIndex): Extracts a substring starting from the specified position.

  • Substring(int startIndex, int length): Extracts a substring starting from the specified position and of a specified length.

  • IndexOf(string value): Finds the position of the first occurrence of a substring.

  • Replace(string oldValue, string newValue): Replaces a substring within the string.

  • Split(char[] separator): Splits the string based on the specified character array.

  • ToLower(): Converts the string to lowercase.

  • ToUpper(): Converts the string to uppercase.

Example Code

using System;

class Program
{
    static void Main()
    {
        string str = "Hello, World!";
        
        // Get string length
        Console.WriteLine("Length: " + str.Length);
        
        // Substring extraction
        Console.WriteLine("Substring: " + str.Substring(7)); // Output: "World!"
        
        // Find position of substring
        Console.WriteLine("IndexOf 'World': " + str.IndexOf("World"));
        
        // Replace substring
        Console.WriteLine("Replace 'World' with 'C#': " + str.Replace("World", "C#"));
        
        // Split string
        string[] parts = str.Split(new char[] { ' ', '!', ',' });
        foreach (string part in parts)
        {
            Console.WriteLine("Split part: " + part);
        }
        
        // Convert to uppercase and lowercase
        Console.WriteLine("ToLower: " + str.ToLower());
        Console.WriteLine("ToUpper: " + str.ToUpper());
    }
}

Regular Expressions

Regular expressions are a powerful tool for text processing, used for matching, searching, replacing, and other complex string operations. C# provides the System.Text.RegularExpressions namespace, which includes classes related to regular expressions.

Common Regular Expression Classes and Methods

  • Regex Class: Represents a regular expression.

    • IsMatch(string input): Checks if the input string matches the regular expression.

    • Match(string input): Finds the first match of the regular expression in the input string.

    • Matches(string input): Finds all matches of the regular expression in the input string.

    • Replace(string input, string replacement): Replaces all parts of the input string that match the regular expression.

Example Code

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "Hello, 12345, world! 67890!";
        
        // Check if the string contains numbers
        Regex regexNumbers = new Regex(@"d+");
        Console.WriteLine("Contains numbers: " + regexNumbers.IsMatch(input));
        
        // Find the first sequence of numbers
        Match match = regexNumbers.Match(input);
        if (match.Success)
        {
            Console.WriteLine("First number: " + match.Value);
        }
        
        // Find all sequences of numbers
        MatchCollection matches = regexNumbers.Matches(input);
        foreach (Match m in matches)
        {
            Console.WriteLine("Found number: " + m.Value);
        }
        
        // Replace numbers with "*"
        string replaced = regexNumbers.Replace(input, "*");
        Console.WriteLine("Replaced: " + replaced);
    }
}

Conclusion

C# provides a variety of string manipulation methods and robust support for regular expressions, making text processing relatively straightforward. Mastering these foundational concepts and techniques can significantly enhance programming efficiency and code quality. Whether it's simple string concatenation and substring extraction or more complex pattern matching and replacement, C# can handle these tasks with ease.