Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string split by index / params?

Tags:

string

c#

split

Just before I write my own function just wanted to check if there exists a function like string.split(string input, params int[] indexes) in the .NET library? This function should split the string on indexes i pass to it.

Edit: I shouldn't have added the string.join sentence - it was confusing.

like image 331
maxp Avatar asked Aug 22 '11 14:08

maxp


People also ask

How do I split a string at a specific index?

To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string.

Can we use index in Split?

Splitting Strings ] Now that we have a new array in the splitString variable, we can access each section with an index number. If an empty parameter is given, split() will create a comma-separated array with each character in the string.

How split a string after a specific character in C#?

Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);


2 Answers

All other answers just seemed too complicated, so I took a stab.

using System.Linq;

public static class StringExtensions
{
    /// <summary>
    ///     Returns a string array that contains the substrings in this instance that are delimited by specified indexes.
    /// </summary>
    /// <param name="source">The original string.</param>
    /// <param name="index">An index that delimits the substrings in this string.</param>
    /// <returns>An array whose elements contain the substrings in this instance that are delimited by one or more indexes.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="index" /> is null.</exception>
    /// <exception cref="ArgumentOutOfRangeException">An <paramref name="index" /> is less than zero or greater than the length of this instance.</exception>
    public static string[] SplitAt(this string source, params int[] index)
    {
        index = index.Distinct().OrderBy(x => x).ToArray();
        string[] output = new string[index.Length + 1];
        int pos = 0;

        for (int i = 0; i < index.Length; pos = index[i++])
            output[i] = source.Substring(pos, index[i] - pos);

        output[index.Length] = source.Substring(pos);
        return output;
    }
}
like image 165
roydukkey Avatar answered Oct 14 '22 01:10

roydukkey


You could use the String instance method Substring.

string a = input.Substring(0, 10);
string b = input.Substring(10, 5);
string c = input.Substring(15, 3);
like image 27
Paul Ruane Avatar answered Oct 14 '22 01:10

Paul Ruane