This question already has answers here:
Split a string by another string in C#
(11 answers)
Closed 6 years ago.
I have a string like this: string ip = "192.168.10.30 | SomeName".
I want to split it by the | (including the spaces. With this code it is not possible unfortunately:
string[] address = ip.Split(new char[] {'|'}, StringSplitOptions.RemoveEmptyEntries);
as this leads to "192.168.10.30 ". I know I can add .Trim() to address[0] but is that really the right approach?
Simply adding the spaces(' | ') to the search pattern gives me an
Unrecognized escape sequence
You can split by string, not by character:
var result = ip.Split(new string[] {" | "}, StringSplitOptions.RemoveEmptyEntries);
The Split method accepts character array, so you can specify the second character as well in that array. Since you ware used RemoveEmptyEntries those spaces will be removed from the final result.
Use like this :
string[] address = ip.Split(new char[] { '|',' '}, StringSplitOptions.RemoveEmptyEntries);
You will get two items in the array
"192.168.10.30" and SomeName
This might do the trick for you
string[] address = ip.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
Related
This question already has answers here:
How do I remove duplicates from a C# array?
(28 answers)
Closed 19 days ago.
The below example splits two strings of codes and appends them together. The problem is it doesn't filter duplicates. In this case allCodes has "DL" twice. Is there a way to do the split & concatenate without dups?
string carCodes = "DL, UL, AL, ";
string airCodes = "RL, DL";
string[] allCodes = airCodes
.Replace(" ", "")
.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Concat(carCodes
.Replace(" ", "")
.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
.ToArray();
A distinct does it.
.Distinct().ToArray();
I saw this in https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-5.0
Each element of separator defines a separate delimiter character. If
two delimiters are adjacent, or a delimiter is found at the beginning
or end of this instance, the corresponding element in the returned
array contains Empty.
string str = "Hello.. How.. are.. you?";
string[] words = str.Split(new char[] { '.' });
foreach (string s in words)
{
MessageBox.Show(s);
}
Outputs are: Hello "" How "" are "" you?
string str = "Hello. How. are. you?";
string[] words = str.Split(new char[] { '.' });
foreach (string s in words)
{
MessageBox.Show(s);
}
Outputs are: Hello How are you?
Why does this happen?
Your split character is .:
string[] words = str.Split(new char[] { '.' });
(the parameter is an array, because you can supply multiple different characters to split on - it does not mean it splits "on an array of dots" if that was your assumption)
So .NET splits accordingly at every dot character:
Hello.. How.. are.. you?
^^ ^^ ^^
The first part is Hello, that gets terminated by the first dot.
The second part is a string of 0 length, because it gets terminated immediately by the second dot.
This question already has answers here:
Split string separated by multiple spaces, ignoring single spaces
(3 answers)
Closed 7 years ago.
Lets say I have a string like this:
"15 Lore ipsum"
Is there a way to split it so I got 3 strings after split ["15", "Lore", "Ipsum"]. So I want delimiter to be a space consisting of two or more spaces, I don't want one space to be delimiter...
You can use string.Split(char[], StringSplitOptions) method:
string s = "15 Lore ipsum";
string result = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
\s stands for "whitespace character".
http://www.w3schools.com/jsref/jsref_regexp_whitespace.asp
Try (.*?)\s+(.*?)\s+(.*?)$
https://regex101.com/r/oH8qY6/1
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));
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