Is there anyway for me to split a string and exclude the last split?
My data looks like this: data1,data2,data3, and so if I split the element the last element in the array will be empty, so I would just prefer to exclude it from the split.
Right now I have this:
serialNumbers = delimitedSerials.ToString().Split(',');
Granted I know I can just leave it and in my for loop just know to skip the last element, but was wondering if there was a simple way to just exclude it at the time of splitting.
you can split it using the StringSplitOptions parameter:
data.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
Below code has a Linq where clause to exclude the empty data
string input ="data1,data2,data3,";
var output = input.Split(',').Where(value => !string.IsNullOrEmpty(value));
foreach(string data in output)
Console.WriteLine(data);
Related
I am working on an application where I have multiple ID in a string that I passed from my view separated by a ';'.
So this is what it looks like "P171;P172".
if (ModelState.IsValid)
{
hiddenIDnumber= hiddenIDnumber.Trim();
List<string> listStrLineElements = hiddenIDnumber.Split(';').ToList();
foreach (string str in listStrLineElements)
The problem is, when I split my hiddenIDnumber, even if I have two numbers, I get a count of 3 and "" is returned (which I believe is an empty space).
When I use a breakpoint i get "P171","P172" AND "".
This is causing my program to fail because of my FK constraints.
Is there a way to "overcome this and somehow "trim" the space out?
Use another overload of string.Split whih allows you to ignore empty entries. For example:
List<string> listStrLineElements = hiddenIDnumber
.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.ToList();
I would say that one way to do this would be to use String Split Options. With String.Split there is an overload that takes two arguments, i.e. it would be like
myString.Split(new [] {';'}, StringSplitOptions.RemoveEmptyEntries);
This should prevent any entries in your array that would only be an empty string.
var listStrLineElements = hiddenIDnumber.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
Use the parameter StringSplitOptions.RemoveEmptyEntries to automatically remove empty entries from the result list.
You can try:
IList<string> listStrLineElements = hiddenIDnumber.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
I prefer this over new [] { ';' } for readability, and return it to an interface (IList<string>).
You will end up with the number of ;s plus one when you split. Since your comment mentions you have 2 ;s, you will get 3 in your list: before the first semicolon, between the first and the second, and after the second. You are not getting an empty space, you are getting a string.Empty because you have nothing after the last ;
if (ModelState.IsValid)
{
hiddenIDnumber= hiddenIDnumber.Trim(";");
List<string> listStrLineElements = hiddenIDnumber.Split(';').ToList();
foreach (string str in listStrLineElements)
This way you get rid of the ; at the end before you split, and you don't get an empty string back.
I have been trying to split a string based on regions enclosed by non escaped quotes, and those between two such substrings.
I have used
var parts = Regex.Split(value, "(\"(?:((\\\\\\\\)*\\\\\\\")|[^\"])*\")");
Now suppose value is
"\"abc\", \"a\\\"b\\\"c\""
parts contains
""
"\"abc\""
", "
"\"a\\\"b\\\"c\""
"\\\""
""
I am unable to figure out why the fifth string is there. Its content is present only inside the contents of the fourth string. Am I using the regex wrong? What is the origin of the string?
According to the StringSplitOptions "Remarks" section:
The String.Split method returns an array of the substrings in a given string that are delimited by specified characters or strings. Adjacent delimiters yield an array element that contains an empty string (""). The values of the StringSplitOptions enumeration specify whether an array element that contains an empty string is included in the returned array.
As for working around this quirk, MethodMan has the right idea: pass the StringSplitOptions.RemoveEmptyEntries argument to Split() to remove those entries.
var content = "\"abc\", \"a\\\"b\\\"c\"";
var spltContent = content.Split(new[] {#"\\\"}, StringSplitOptions.RemoveEmptyEntries);
this will be your out put
"\"abc\", \"a\\\"b\\\"c\""
I'm not entirely sure what your attempting to do, but I believe it is as follows:
var content = "\"abc\", \"a\\\"b\\\"c\"";
var filter = Regex.Split(content, #"(?<=[,\s]\"")(.*?)(?=\"")");
foreach(var item in filter)
Console.WriteLine(item);
The output would be as follows:
"abc", "
a\
"b\"c"
This should ignore your escape, but grab items within a quote even as nested as you've noticed.
Hopefully this helps.
I'm reading a comma-delimited list of strings from a config file. I need to check the following steps
1) check to see if the string has `[`, if it is then remove or ignore...
2) split `,` `-` //which i am doing below...
Here is what I able to do so far;
string mediaString = "Cnn-[news],msnbc";
string[] split = mediaString.Split(new Char[] { ',', '-' }); //gets me the bracket
what I want is to ignore/remove the string which is in the brackets so the end result should be like this:
mediaString =
Cnn
msnbc
Using Linq:
mediaString.Split(new Char[] { ',', '-' }).Where(val => !val.Contains('[')
You can make the test (val.Contains(...)) as sophisticated as you like (e.g. starts and ends with, regular expression, specific values, call an object provided via a DI framework if you want to get all enterprisey).
Use Regex replace to clean your string
string str = #"Cnn-[news],msnbc";
Regex regex = new Regex(#"\[.*\]");
string cleanStr = regex.Replace(str, "");
string[] split = cleanStr.Split(new Char[] { ',', '-' });
Without using LINQ or regex:
Split your string as you are doing now.
Create a data structure of string type for example: List.
Run over the results array and for each entry check it contains the specified character, if it doesn't add it to the List.
In the end you should have a List with the required result.
This The regex solution is far more elegant but if you cannot use reg ex this one should do it
I have the following expression:
"<p>What ?</p>\n<pre>Starting Mini</pre>"
When I perform a split as follows:
var split = content
.Split(new[] { "<pre>", "</pre>" }, StringSplitOptions.None);
Then it gives me three entries:
"<p>What ?</p>\n"
"Starting Mini"
""
Why does it give an empty line as the third entry and how can I avoid this?
The "why" is simply: the input (if you don't remove empty entries) will always "split" at any occurrence of the separator(s), so if the separator(s) appear n times in the string, then the array will be n+1 long. In particular, this essentially lets you know where they occurred in the original string (although when using multiple separators, it doesn't let you know which appeared where).
For example, with a simple example (csv without any escaping etc):
string[] arr = input.Split(','); // even if something like "a,b,c,d,"
// which allows...
int numberOfCommas = arr.Length - 1;
string original = string.Join(",", arr);
The fix is, as already mentioned, to use RemoveEmptyEntries.
Use StringSplitOptions.RemoveEmptyEntries instead to remove empty string in list
var split = content
.Split(new[] { "<pre>", "</pre>" }, StringSplitOptions.RemoveEmptyEntries);
You get this behaviour as specified from Microsoft:
"Adjacent delimiters yield an array element that contains an empty string ("")."
So since you have the last pre you get the last empty array element
Mailou, instead of giving 'StringSplitOptions.None' try 'StringSplitOptions.RemoveEmptyEntries'. It removes the the empty lines.
The reason you are getting this behaviour is that your one of the delimeter </pre> happens to exist at the end of the string.
You may see: string.Split - MSDN
...a delimiter is found at the beginning or end of this instance, the
corresponding array element contains Empty
To overcome this:
Use StringSplitOptions.RemoveEmptyEntries instead of StringSplitOptions.None
StringSplitOptions.RemoveEmptyEntries - MSDN
The return value does not include array elements that contain an empty
string
var split = content
.Split(new[] { "<pre>", "</pre>" }, StringSplitOptions.RemoveEmptyEntries);
You also need to specify the
StringSplitOptions.RemoveEmptyEntries enumerator.
The split string[] values not include any empty string by using StringSplitOptions.RemoveEmptyEntries
var split = content
.Split(new[] { "<pre>", "</pre>" }, StringSplitOptions.RemoveEmptyEntries);
Reference: StringSplitOptions Enumeration
You are getting empty line due to
</pre>
You are instructing split function to split by <pre> and </pre>
As result with <pre> you are getting
<p>What ?</p>\n
Starting Mini</pre>
And next result is with </pre> is
<p>What ?</p>\n
Starting Mini
...
I have the following return of a printer:
{Ta005000000000000000000F 00000000000000000I 00000000000000000N 00000000000000000FS 00000000000000000IS 00000000000000000NS 00000000000000000}
Ok, I need to save, in a list, the return in parts.
e.g.
[0] "Ta005000000000000000000F"
[1] "00000000000000000I"
[2] "00000000000000000N"
...
The problem is that the number of characters varies.
A tried to make it going into the 'space', taking the substring, but failed...
Any suggestion?
Use String.Split on a single space, and use StringSplitOptions.RemoveEmptyEntries to make sure that multiple spaces are seen as only one delimiter:
var source = "00000000000000000FS 0000000...etc";
var myArray = source.Split(' ', StringSplitOptions.RemoveEmptyEntries);
#EDIT: An elegant way to get rid of the braces is to include them as separators in the Split (thanks to Joachim Isaksson in the comments):
var myArray = source.Split(new[] {' ', '{', '}'}, StringSplitOptions.RemoveEmptyEntries);
You could use a Regex for this:
string input = "{Ta005000000000000000000F 00000000000000000I 00000000000000000N 00000000000000000FS 00000000000000000IS 00000000000000000NS 00000000000000000}";
IEnumerable<string> matches = Regex.Matches(input, "[0-9a-zA-Z]+").Select(m => m.Value);
You can use string.split to create an array of substrings. Split allows you to specify multiple separator characters and to ignore repeated splits if necessary.
You could use the .Split member of the "String" class and split the parts up to that you want.
Sample would be:
string[] input = {Ta005000000000000000000F 00000000000000000I 00000000000000000N 00000000000000000FS 00000000000000000IS 00000000000000000NS 00000000000000000};
string[] splits = input.Split(' ');
Console.WriteLine(splits[0]); // Ta005000000000000000000F
And so on.
Just off the bat. Without considering the encompassing braces:
string printMsg = "Ta005000000000000000000F 00000000000000000I
00000000000000000N 00000000000000000FS
00000000000000000IS 00000000000000000NS 00000000000000000";
string[] msgs = printMsg.Split(' ').ForEach(s=>s.Trim()).ToArray();
Could work.