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)
Related
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));
}
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
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
How can I split a word from within brackets like:
(animal)
I need to take only the word "animal" using C# split.
If you only want to split on brackets this will do:
string test = "(duck)(monkey)";
string[] animals = test.Split(new [] {'(', ')'},
StringSplitOptions.RemoveEmptyEntries);
animals now contains { "duck", "monkey"}. For a single animal input (i.e. (animal)) just take animals[0] or evaluate directly:
string animal = test.Split(new [] {'(', ')'},
StringSplitOptions.RemoveEmptyEntries)[0];
The documentation for the String.Split method already gives you examples of how to do this. Just specify the brackets as the delimiter characters you want to split on:
string originalString = "(animal)";
string[] newString = originalString.Split(new char[] {'(', ')'});
Output:
{"", "animal", ""}
Are you sure you need to use split()?
If it is as simple as you stated wouldn't
string justWord = "(animal)".Replace("(","").Replace(")","")
be more efficient and clearer?
Only the trim is enough to do this
string originalString = "(animal)";
originalString = originalString.Trim('(',')');
Here is
string searchValues = "(duck)(monkey)";
var matches = Regex.Matches(searchValues, #"\w+");
var values = (from matche in matches.Cast<Match>() select matche.Value).ToList();
How do I split a string with a string in C# .net 1.1.4322?
String example:
Key|Value|||Key|Value|||Key|Value|||Key|Value
need:
Key|Value
Key|Value
Key|Value
I cannot use the RegEx.Split because the separating character is the ||| and just get every character separately.
I cannot use the String.Split() overload as its not in .net 1.1
Example of Accepted solution:
using System.Text.RegularExpressions;
String[] values = Regex.Split(stringToSplit,"\\|\\|\\|");
What about using #"\|\|\|" in your Regex.Split call? That makes the | characters literal characters.
One workaround is replace and split:
string[] keyvalues = "key|value|||key|value".replace("|||", "~").split('~');
here is an example:
System.Collections.Hashtable table;
string[] items = somestring.split("|||");
foreach(string item in items)
{
string[] keyvalue = item.split("|");
table.add(keyvalue[0],keyvalue[1]);
}
string input = "Hi#*#Hello#*#i#*#Hate#*#My#*#......" ;
string[] delim = new string[] { "#*#" };
string[] results = input.split(delim , StringSplitOptions.None);