ASP.NET C# String.Split - c#

I want to split a string if there is a space between words.
For example:
"Blood Doner Jack Stv 240 o+"
When I split it using a single space it returns an array object with 6 items, but if I try it with the same set of text and there are 2 spaces in place of one it increase the array to 7:
"Blood Doner Jack Stv 240 o+"
So I want to know how to remove split it with a double space as well as a single.
I know I can use Replace() with 2 spaces to 1 space but what if I have 3 or 4 spaces?
Thanks in advance!

You can use the overload of String.Split which takes a StringSplitOptions:
string[] bits = text.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Note that to avoid creating a char array on each call, you could use:
private static readonly char[] SplitSeparators = {' '};
...
string[] bits = text.Split(SplitSeparators,
StringSplitOptions.RemoveEmptyEntries);

just use StringSplitOptions.RemoveEmptyEntries:
var s = "Blood Doner Jack Stv 240 o+";
var arr = s.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
Or you can replace many spaces with one using Regexp, and than Split:
string str = System.Text.RegularExpressions.RegEx.Replace(s ,#"\s+"," ");
var arr = str.Split(new[] {" "}, StringSplitOptions.None);

This will remove spaces:
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
Then you can split normally
How do I replace multiple spaces with a single space in C#?
How to remove extra space between two words using C#?

string s1 = "Blood Doner Jack Stv 240 o+";
Regex r = new Regex(#"\s+");
string s2 = r.Replace(s1, #" ");
string[] s3 = s2.Split(' ');

Related

Split string with variable number of spaces [duplicate]

This question already has answers here:
Splitting string based on variable number of white spaces
(2 answers)
Closed 8 years ago.
I'm trying to split a string like this:
7 300685 1235 200017 200018 200019
In
7
300685
1235
200017
200018
200019
array of strings.
I've come up with this Regex but it keeps the white spaces too:
var myStrings = System.Text.RegularExpressions.Regex.Split(linea, #"\s+");
That's because I target any string that preceeds a white space. How to not to do that and keep only not white strings.
I know that it is easily done by removing empty strings from the array but I would like to do it with the regular expression.
You can use StringSplitOptions.RemoveEmptyEntries enumeration with String.Split method like;
The return value does not include array elements that contain an empty
string
string s = "7 300685 1235 200017 200018 200019";
var array = s.Split(new []{" "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array)
{
Console.WriteLine(item);
}
Output will be;
7
300685
1235
200017
200018
200019
Here a demonstration.
Why don't you just use String.Split method ?
var myStrings = linea.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Another way with Split and LINQ without RemoveEmptyEntries option:
var myStrings = linea.Split().Where(x => x.All(char.IsDigit)).ToArray();
Also there is a RegexOption.IgnorePatternWhitespace parameter that you can pass your Regex.Split method to remove whitespaces:
var myStrings = Regex.Split(linea, #"\s+", RegexOptions.IgnorePatternWhitespace);
I would suggest to simply use string.Split:
string[] s = yourString.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
See MSDN.
Why does this not work for you:
string str = "7 300685 1235 200017 200018 200019";
str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
You can also use String.Trim to remove all leading and trailing occurrences of a set of white-space characters.
Try this
string[] splitvalue = string.Split(str, ' ', StringSplitOptions.RemoveEmptyEntries);
or:
string[] splitvalue = str.Split(null);
or:
string[] splitvalue = str.Split(new char[0]);
var list = "Your String".Split(' ').Where(p =>!string.IsNullOrWhiteSpace(p));

Regex to take values based on multiple checks

I have string
string s="someMethod(999,'xyz')"
and I want to take 999 and xyz in to array.
what could be the best possible way instead of splitting it by '(' first
and by ',' and then by '\''
You don't need to use regex for that.
You can use String.Substring, String.IndexOf and String.Split methods like;
string s = "someMethod(999,'xyz')";
string BetweenBrackets = s.Substring(s.IndexOf("(") + 1, s.IndexOf(")") - s.IndexOf("(") - 1);
string[] array = BetweenBrackets.Split(new char[] { ',', '\'' }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(array[0]); //999
Console.WriteLine(array[1]); //xyz
Here a DEMO.
Try this regex:
^.+?\((.+?),'(.+?)'\)$
$1: 999,
$2: xyz
Full code:
Regex r = new Regex(#"^.+?\((.+?),'(.+?)'\)$");
string[] parameters = new string[2];
parameters[0]=r.Match(s).Groups[1].Value;
parameters[1]=r.Match(s).Groups[2].Value;
If you're not sure that there will be single quotes, use '? instead of '

How to break a string at each comma?

Hi guys I have a problem at hand that I can't seem to figure out, I have a string (C#) which looks like this:
string tags = "cars, motor, wheels, parts, windshield";
I need to break this string at every comma and get each word assign to a new string by itself like:
string individual_tag = "car";
I know I have to do some kind of loop here but I'm not really sure how to approach this, any help will be really appreciate it.
No loop needed. Just a call to Split():
var individualStrings = tags.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
You can use one of String.Split methods
Split Method (Char[])
Split Method (Char[], StringSplitOptions)
Split Method (String[], StringSplitOptions)
let's try second option:
I'm giving , and space as split chars then on each those character occurrence input string will be split, but there can be empty strings in the results. we can remove them using StringSplitOptions.RemoveEmptyEntries parameter.
string[] tagArray = tags.Split(new char[]{',', ' '},
StringSplitOptions.RemoveEmptyEntries);
OR
string[] tagArray = s.Split(", ".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries);
you can access each tag by:
foreach (var t in tagArray )
{
lblTags.Text = lblTags.Text + " " + t; // update lable with tag values
//System.Diagnostics.Debug.WriteLine(t); // this result can be see on your VS out put window
}
make use of Split function will do your task...
string[] s = tags.Split(',');
or
String.Split Method (Char[], StringSplitOptions)
char[] charSeparators = new char[] {',',' '};
string[] words = tags.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
string[] words = tags.Split(',');
You are looking for the C# split() function.
string[] tags = tags.Split(',');
Edit:
string[] tag = tags.Trim().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
You should definitely use the form supplied by Justin Niessner. There were two key differences that may be helpful depending on the input you receive:
You had spaces after your ,s so it would be best to split on ", "
StringSplitOptions.RemoveEmptyEntries will remove the empty entry that is possible in the case that you have a trailing comma.
Program that splits on spaces [C#]
using System;
class Program
{
static void Main()
{
string s = "there, is, a, cat";
string[] words = s.Split(", ".ToCharArray());
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}
Output
there
is
a
cat
Reference

what is the cleanest way to remove all extra spaces from a user input comma delimited string into an array

A program has users typing in a comma-delimited string into an array:
basketball, baseball, soccer ,tennis
There may be spaces between the commas or maybe not.
If this string was simply split() on the comma, then some of the items in the array may have spaces before or after them.
What is the best way of cleaning this up?
You can use Regex.Split for this:
string[] tokens = Regex.Split("basketball, baseball, soccer ,tennis", #"\s*,\s*");
The regex \s*,\s* can be read as: "match zero or more white space characters, followed by a comma followed by zero or more white space characters".
string[] values = delimitedString.Split(',').Select(s => s.Trim()).ToArray();
string s = "ping pong, table tennis, water polo";
string[] myArray = s.Split(',');
for (int i = 0; i < myArray.Length; i++)
myArray[i] = myArray[i].Trim();
That will preserve the spaces in the entries.
You can split on either comma or space, and remove the empty entries (those between a comma and a space):
string[] values = delimitedString.Split(new char[]{',',' '}, StringSplitOption.RemoveEmptyEntries);
Edit:
However, as that doesn't work with values that contain spaces, instead you can split on the possible variations if your values can contain spaces:
string[] values = delimitedString.Split(new string[]{" , ", " ,", ", ", ","}, StringSplitOptions.None);
Split the items on the comma:
string[] splitInput = yourInput.Split(',', StringSplitOption.RemoveEmptyEntries);
and then use
foreach (string yourString in splitInput)
{
yourString.Trim();
}
String.Replace(" ","") before you split the string
I would firstly split a text by ",", and then use Trim method to remove spaces on start and end of the each string. This will add support for string with spaces to your code.

string.split - by multiple character delimiter

i am having trouble splitting a string in c# with a delimiter of "][".
For example the string "abc][rfd][5][,][."
Should yield an array containing;
abc
rfd
5
,
.
But I cannot seem to get it to work, even if I try RegEx I cannot get a split on the delimiter.
EDIT: Essentially I wanted to resolve this issue without the need for a Regular Expression. The solution that I accept is;
string Delimiter = "][";
var Result[] = StringToSplit.Split(new[] { Delimiter }, StringSplitOptions.None);
I am glad to be able to resolve this split question.
To show both string.Split and Regex usage:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, #"\]\[");
string tests = "abc][rfd][5][,][.";
string[] reslts = tests.Split(new char[] { ']', '[' }, StringSplitOptions.RemoveEmptyEntries);
Another option:
Replace the string delimiter with a single character, then split on that character.
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');
Regex.Split("abc][rfd][5][,][.", #"\]\]");
More fast way using directly a no-string array but a string:
string[] StringSplit(string StringToSplit, string Delimitator)
{
return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}
StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/
In .NETCore 2.0 and beyond, there is a Split overload that allows this:
string delimiter = "][";
var results = stringToSplit.Split(delimiter);
Split (netcore 2.0 version)

Categories