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.
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.
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.
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);
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;
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With