Net-informations.com
SiteMap  | About    

How to use C# string Split



C# Split() handles splitting upon given string and character delimiters. It returns an array of String containing the substrings delimited by the given System.Char array.

split-string-csharp

If your String contains "dd-mm-yy", split on the "-" character to get an array of: "dd" "mm" "yy".

The String Split method ignores any element of separator whose value is null or the empty string ("").

Syntax :

Parameters:

  1. Separator - the given delimiter

Returns:

  1. An array of Strings delimited by one or more characters in separator.

Output:

C# String Split Example

How to split strings using regular expressions

The Regular Expressions Split() methods are almost similar to the String.Split() method, except that Regex.Split() method splits the string at a delimiter determined by a Regular Expression instead of a set of characters.

When using Regular Expressions you should use the following namespace in your project.

Output:

c# String Split by multiple characters delimiter

We can split a string by multiple character delimiter using String.split() method.

Output:

Using Regular Expressions for multiple characters

C# String Split by multiple characters delimiter using Regular Expressions

Output:

C# String split New Line

You can split a string on a new line or carriage return using the delimiter "\r\n".

C# String split Carriage Return

Output:

Environment.NewLine

Also you can use Environment.NewLine to remove the new line from a string

Output:

How to split() a delimited string to a List < String >

You can retrieve the result of a String splt() method to a C# List. The following program convert the String Array to a List.

C# Convert List to String

C# String split White spaces

StringSplitOptions.RemoveEmptyEntries guarantees the return value does not include array elements that contain an empty string. The following C# program shows how to remove all white spaces from string using StringSplitOptions.RemoveEmptyEntries.





using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string myStrA = "one two   three    four     five";
            string[] result = myStrA.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in result)
                MessageBox.Show(s);

        }
    }
}

When you execute this C# program you will get the result removing all white spaces from the string





net-informations.com (C) 2019    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.