Splits a given string at the first occurrence of any of the given splitters. - CSharp System

CSharp examples for System:String Split

Description

Splits a given string at the first occurrence of any of the given splitters.

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;//  w ww .  java 2s  .c om

public class Main{
        /// <summary>
		/// Splits a given string at the first occurrence of any of the given splitters.
		/// </summary>
		/// <param name="source">The string to be split.</param>
		/// <param name="splitters">A set of strings to split the string by. Only one is used.</param>
		/// <returns>
		/// An array containing two strings.
		/// The first is the string prior to the first occurrence of the splitter.
		/// The second is the string after the first occurrence of the splitter.
		/// </returns>
		public static string[] SplitOnce(this string source, params string[] splitters)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			string[] parts = source.Split(splitters, StringSplitOptions.None);
			string remainder = source.Substring(parts[0].Length);
			foreach (string splitter in splitters)
			{
				if (remainder.StartsWith(splitter))
				{
					remainder = remainder.Substring(splitter.Length);
					break;
				}
			}
			return new string[] { parts[0], remainder };
		}
        /// <summary>
		/// Splits a string at the first occurrence of a given splitter string and returns both parts.
		/// Neither parts contains the splitter.
		/// </summary>
		/// <param name="source">The string to be split.</param>
		/// <param name="splitter">The string that splits the source in two parts.</param>
		/// <returns>
		/// An array containing two strings.
		/// The first is the string prior to the first occurrence of the splitter.
		/// The second is the string after the first occurrence of the splitter.
		/// </returns>
		public static string[] SplitOnce(this string source, string splitter)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (splitter == null)
			{
				throw new ArgumentNullException("splitter");
			}
			string[] parts = source.Split(new string[] { splitter }, StringSplitOptions.None);
			string remainder = string.Join(splitter, parts.Skip(1));
			return new string[] { parts[0], remainder };
		}
}

Related Tutorials