Skip to main content
Published on

Methods I in C#

Share:

Introduction

The C# language offers a variety of built-in methods for working with strings. In this article, we will focus on two specific methods: Substring() and Split(). Both are essential for developers who want to manipulate and analyze data in string format.

Substring() Method

Concept

Substring() is one of the most widely used methods when it comes to manipulating strings. It allows you to extract a specific part of a string, making it easier to analyze and transform data.

How does it work?

The method has two variants:

  • Substring(start): Returns a substring from the specified index to the end.
  • Substring(start, length): Extracts a substring based on the start index and the specified length.

Use cases

Imagine you are dealing with product codes that have a specific structure, such as "PROD-12345-XYZ". If you want to extract only the product number, Substring() would be a useful tool.

Split() Method

Concept

Split() is fundamental for dividing strings based on specific delimiters. It is frequently used in situations where data is received in a delimited format, such as CSV.

How does it work?

The method splits the original string into an array of strings, based on the delimiter or pattern provided.

Use cases

If you are working with transaction logs that are stored in a comma-delimited format, Split() can be used to split each entry and analyze the data more easily.

using System;
using System.Text.RegularExpressions;

namespace Base {
  class MethodsI {
    private string oneTwoThree = "OneTwoThree", name = "Nelson Gomes da Silva";

    public void Run() {
      // Substring() demonstration
      Console.WriteLine($"Example 1: {oneTwoThree.Substring(0, 2)}");
      Console.WriteLine($"Example 2: {oneTwoThree.Substring(2, 4)}");
      Console.WriteLine($"Example 3: {oneTwoThree.Substring(6)}");

      // Split() demonstration
      var words = name.Split(' ');

      foreach (var word in words)
        Console.WriteLine($"Split word: {word}");

      var _words = Regex.Split(name, " Gomes da ");
      Console.WriteLine($"Split name: {_words[0]} {_words[1]}");
    }
  }
}

Conclusion

Mastering string manipulation is fundamental in programming, and the Substring() and Split() methods are key tools in this process. Whether for data analysis, transformation, or simple manipulation, knowing and understanding these methods will enrich and optimize your code.

Happy coding!