C# splitting a string with multiple seperator - c#

user1;user2;user3;user4 user1
I'd like to split these strings so I can iterate over all of them to put them in objects. I figured I could use
myString.split(";")
However, in the second example, there is no ; , so that wouldn't do the trick. What would be the best way to do this when it can be variable like this?
Thanks

You can use overload taking multiple separators:
myString.Split(new[] { ";", " " }, StringSplitOptions.RemoveEmptyEntries);

No need for a regex. The split method can take a list of separators
"user1;user2;user3;user4 user1".Split(';', ' ')
outputs
string[5] { "user1", "user2", "user3", "user4", "user1" }

You can use the regex
"[ ;]"
the square brackets define a character class - matches one of the characters between the brackets.

You can use overload of Split() method which take an array of seperator
string myString = "user1;user2;user3;user4 user1";
string[] stringSeparators = new string[] { ";", " " };
string[] s = myString.Split(stringSeparators, StringSplitOptions.None);

the following test pass!
[TestCase("user1;user2;user3;user4 user1", 5)]
public void SplitString(string input, int expectedCount)
{
Assert.AreEqual(expectedCount, input.Split(new []{";"," "},StringSplitOptions.RemoveEmptyEntries));
}

Related

Split string by second comma, then by third comma

I have a string which looks like this:
Less than $5,000, $5,000-$9,999, $10,000-$14,999, $45,000-$49,999, $50,000-$54,999
And what I would like to have is:
Less than $5,000 or $5,000-$9,999 or $10,000-$14,999 or $45,000-$49,999 or $50,000-$54,999
What I tried is:
items[1].Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(e => new AnswerModel { Name = e }).ToList()
Name should be "Less than $5,000" then "$5,000-$9,999" and so on.
But it splits by every comma, I would need to split it first by the second and then by the third.
What would be the best approach?
Maybe you can split by ", "
string s = "Less than $5,000, $5,000-$9,999, $10,000-$14,999, $45,000-$49,999, $50,000-$54,999";
string result = string.Join(" or ", s.Split(new []{", "},StringSplitOptions.None));
Returns your desired result:
Less than $5,000 or $5,000-$9,999 or $10,000-$14,999 or
$45,000-$49,999 or $50,000-$54,999
If your string looks exactly as you pasted here, and it will always have such pattern, then you can split on a string of two characters:
items[1].Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
Update:
But if your string is without spaces, then you should replace first with some unique character like |, and then split over that new character:
items[1].Replace(",$", "|$").Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
Also you can replace it with or $ and the string would be already in desired format, and there would be no need to split and join again.
This should do the trick.

Find link in a string by regex

So i have a String like so
String org = "Go to http://Apple.com, to see the new Ipad";
How do i return a list of all the words in the String including the url?
For example. The above string should return this list
List<String> chopped = new List<String>(){"Go", "to", "http://Apple.com", " to", "see" , " the", " new", " Ipad"};
I am doing this because i want to reconstruct the string but use the link for something else.
Use string.Split method:
string[] chopped = org.Split(' ');
It returns array of string instead of List<string>.
But you'll still have to take care of characters like ,. You can try doing following:
string []chopped = org.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
It will split using both a space and a comma and return results ignoring empty ones.

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

How can I split a string with a string delimiter? [duplicate]

This question already has answers here:
How do I split a string by a multi-character delimiter in C#?
(10 answers)
Closed 4 years ago.
I have this string:
"My name is Marco and I'm from Italy"
I'd like to split it, with the delimiter being is Marco and, so I should get an array with
My name at [0] and
I'm from Italy at [1].
How can I do it with C#?
I tried with:
.Split("is Marco and")
But it wants only a single char.
string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);
If you have a single character delimiter (like for instance ,), you can reduce that to (note the single quotes):
string[] tokens = str.Split(',');
.Split(new string[] { "is Marco and" }, StringSplitOptions.None)
Consider the spaces surronding "is Marco and". Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and " as separator...
You are splitting a string on a fairly complex sub string. I'd use regular expressions instead of String.Split. The later is more for tokenizing you text.
For example:
var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy");
Try this function instead.
string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);
You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.
You can also use regular expression. A simple google search turned out with this
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string value = "cat\r\ndog\r\nanimal\r\nperson";
// Split the string on line breaks.
// ... The return value from Split is a string[] array.
string[] lines = Regex.Split(value, "\r\n");
foreach (string line in lines) {
Console.WriteLine(line);
}
}
}
Read C# Split String Examples - Dot Net Pearls and the solution can be something like:
var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);
There is a version of string.Split that takes an array of strings and a StringSplitOptions parameter:
http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

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