2

In Python, you can get the substring before, and after a string. An example being...

myString = "Hello, World!".partition(", ")
print(myString[0], myString[2]) # Index 0 is the substring before ", ", and 2 being the index after ", ".
print(myString)

The code above should output

Hello World!
['Hello', ', ', 'World!']

Is there any function I can use in C# that allows for this same type of action?

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
Expliked
  • 101
  • 10
  • Though there is a little difference between string.Split in C# and parition() in python, I think the link answers OP's question. Closing this question. – Cheng Chen Sep 21 '20 at 03:23

2 Answers2

3

Basic example using String.Split():

void Main()
{
    string myString = "Hello, World!";

    var x = myString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);

    foreach (var s in x)
    {
        Console.WriteLine(s);       
    }
}

Probably better to use "," (without the space) as a delimiter and Trim() results

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • 1
    This works for me, and also thanks for mentioning `Trim()`. This makes another thing I'm doing in my project much easier. – Expliked Sep 21 '20 at 03:33
1

There is no such method built into the .NET standard. You can easily recreate it in C#.

From the docs, this is what partition is supposed to do:

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

We can use IndexOf and Substring to implement this in C#.

public static class StringExtensions {
    public static (string, string, string) Partition(this string str, string sep) {
        int index = str.IndexOf(sep); // find the index
        if (index >= 0) { // if found, get the substrings
            return (str.Substring(0, index), sep, str.Substring(index + sep.Length));
        } else {
            return (str, "", "");
        }
    }
}

Usage:

var result = "Hello, World".Partition(", ");
Console.WriteLine(result.Item1); // Hello
Console.WriteLine(result.Item3); // World
Sweeper
  • 213,210
  • 22
  • 193
  • 313