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();
Related
This question already has answers here:
Remove characters from C# string
(22 answers)
Closed 1 year ago.
I need to delete \, ", [ and ] from this string:
"[\"30001|410000000|400000000|PocketPC_Login|1\",\"30002|420000000|400000000|PocketPC_ChangementZone|1\",\"30003|430000000|400000000|PocketPC_Transactions|1\",\"30004|440000000|400000000|PocketPC_Gestion|1\",\"30005|450000000|400000000|PocketPC_Administration|0\",\"30006|431000000|430000000|PocketPC_TSEntrees|1\"]"
When I do this:
string.Trim(new Char[] { '"', '[', ']', "\\"})
or this:
string.Trim(new Char[] { '"', '[', ']', Convert.ToChar(92)})
the result is always the same:
"30001|410000000|400000000|PocketPC_Login|1\",\"30002|420000000|400000000|PocketPC_ChangementZone|1\",\"30003|430000000|400000000|PocketPC_Transactions|1\",\"30004|440000000|400000000|PocketPC_Gestion|1\",\"30005|450000000|400000000|PocketPC_Administration|0\",\"30006|431000000|430000000|PocketPC_TSEntrees|1"
The \ and " still there. What could I do?
Trim only removes items at the start or the end of a string. You should use a chain of string.Replace.
myString
.Replace("\\", String.Empty)
.Replace("\"", String.Empty)
.Replace("[", String.Empty)
.Replace("]", String.Empty);
Something else I just noticed, is that your data is likely to be JSON (the square brackets [] suggest that you have an array of strings).
This question already has answers here:
c# split string and remove empty string
(6 answers)
Regex : how to get words from a string (C#)
(6 answers)
Closed 2 years ago.
I am working on an requirement where I need to get all the words from a string into an array.
A 'word' is described as any sequence of non-space charachters.
There can be any number of whitespace charachters present in the string.
Input Examples :
" Hello World!! "
"Hello World!!"
" Hello World!! "
In all above cases the output should be ["Hello","World!!"]
Now I have tried to solve the example myself and have below code :
public string[] GetWords(string s)
{
s=s.Trim();
while(s.Contains(" "))
{
s = s.Replace(" ", " ");
}
string[] input=s.Split(' ');
return input;
}
I am getting correct result using the above code. My concerns is there any way the code can be made clean or more optimized than it currently is.
Use the following code snippet:
var str = " Hello World!! ";
string[] array = str.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
The result will be ["Hello","World!!"]
Note: new Char[] { ' ' } if multiple characters need to be handled. Otherwise, you can use the following
string[] array = str.Split(' ', StringSplitOptions.RemoveEmptyEntries);
I would use a regular expression:
using System.Text.RegularExpressions;
...
public string[] GetWords(string s) =>
Regex.Matches(s, #"[^\s]+")
.Cast<Match>()
.Select(x => x.Value)
.ToArray();
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();
This question already has answers here:
Convert `List<string>` to comma-separated string
(6 answers)
Closed 7 years ago.
I have a list of string (List<String>). I want to concatenate list items and form a new comma separated string. I am knew in C#. Please provide me best possible solutions.
string[] myList = ...
string concatenated = string.Join("," myList);
In case you need to create CSV (Comma Separated Value) string
List<String> source = new List<String>() {
"abc", // just a string
"d,e", // string which contains comma
"x\"yz", // string which contains quotation
};
String result = String.Join(",", source
.Select(x => x.Contains(',') || x.Contains('"')
? "\"" + String.Concat(x.Select(c => c == '"' ? "\"\"" : c.ToString())) + "\""
: x));
...
// abc,"d,e","x""yz"
Console.Write(result);
Note quotations marks added
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));