Split Function in c# not working properly - c#

static void Main(string[] args)
{
string Var = ",A,,,B,,C";
string[] members = Var.Split(',');
foreach (string member in members)
{
Console.WriteLine(member);
}
Console.WriteLine(members.Length);
Console.ReadLine();
}
The output of the above code is
A
B
C
7
the 7 is length of the array , but my question is that when i passed ','
in parameters of split function.
so why it takes initial ',' as a space . and why it takes 2 out of 3 ',' as space after A . and why it takes 1 out of 2 ',' as space after B ?

The answer for you question is, this is not space but this is empty string
string can be empty and you are seeing this as space.
,, <- after , we have nothing, so split method adds empty string.
If you want to remove this, you have to put after ',' StringSplitOptions
Var.Split(new char [] {','}, StringSplitOptions.RemoveEmptyEntries);
doc: https://msdn.microsoft.com/pl-pl/library/tabh47cf(v=vs.110).aspx

/For this Question only the function "split()" counts. we can give any special character to split the array elements.
Note: It is not applicable for special characters like single quotations and double quotations/
string Var = "-%%A-,,$$,-B-##%-C";
string[] members = Var.Split('-',',','#','$','%');
foreach (string member in members)
{
Console.WriteLine(member);
}
Console.WriteLine(members.Length);
Console.ReadLine();
The Image shows the output console screen:
https://i.stack.imgur.com/aArY5.png

because you have a space before first ',' and because there is only one place holder between B and C?

Related

element of separator and split function

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.

C# check one count of a splitstring and print another count if correct

So I'm currently working on a program that reads a large txt file line by line as strings. For a particular section of the file the format is like this:
text1 : text2 : text3 : text4 : text5 : text6
I know how to split the string and find different counts.
What I want to do is check that the text in text5 starts with a certain expression SORT, and then for that line print text3.
foreach (string str in File.ReadLines(#"/filelocation"))
{
if (str.StartsWith("fusedef"))
{
string text3 = str.Split(':')[2];
string text5 = str.Split(':')[4];
if (text5.StartsWith("SORT_"))
{
Console.WriteLine(text3);
}
}
(As far as I know, counting a split string starts at 0 but correct me if I'm wrong, only started c# a few weeks ago. Thanks!)
You need to remove any char that could potentially confuse the StartsWith. In particular those empty spaces before the string start.
There is an overload of string.Split that allows you to set more than one char to split on and then remove eventually empty strings returned by this split
string[] blocks = str.Split(new char[] {':', ' '}, StringSplitOptions.RemoveEmptyEntries);
if (blocks[4].StartsWith("SORT_"))
{
Console.WriteLine(blocks[2]);
}
In alternative you could Trim the blocks strings
string[] blocks = str.Split(':');
if (blocks[4].Trim().StartsWith("SORT_"))
{
Console.WriteLine(blocks[2]);
}
Splitting the string will output a string array. To really make use of C# and how simple you can make things why not try operating on your string using a List?
If you know the order that items will appear in you can just call up a string from any position in your list.
foreach (string str in File.ReadLines(#"/filelocation")) {
if (str.StartsWith("fusedef")) {
List<string> list = str.Split(':').ToList();
if (list[5].StartsWith("SORT_"))
Console.WriteLine(list[3]);
}
}
Hope this helps!
Edit: you may want to remove the leading and trailing spaces from your separator. or split your string using ' : ' rather than ':'.

Trim space in <list>string C#

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.

how to deal with string.split by position

I'd like to ask one question about String.Split
For example:
char[] semicolon=new [] {';'};
char[] bracket=new [] {'[',']'};
string str="AND[Firstpart;Sndpart]";
I can split str by bracket and then split by semicolon.
Finally,I get the Firstpart and Sndpart in the bracket.
But If str="AND[AND[Firstpart;Sndpart];sndpart];
How can I get AND[Firpart;Sndpart] and sndpart?
Is there a way to tell c# to split by second semicolon?
Thanks for your help
One way is to hide characters inside bracket with a character that is not used in any of your strings.
Method HideSplit: This method will change separator characters inside brackets with fake ones. Then it will perform split and will give back the result with original characters.
This method maybe an overkill if you want to do this many times. but you should be able to optimize it easily if you got the idea.
private static void Main()
{
char[] semicolon = new[] { ';' };
char[] bracket = new[] { '[', ']' };
string str = "AND[AND[Firstpart;Sndpart];sndpart]";
string[] splitbyBracket = HideSplit(str, bracket);
}
private static string[] HideSplit(string str,char[] separator)
{
int counter = 0; // When counter is more than 0 it means we are inside brackets
StringBuilder result = new StringBuilder(); // To build up string as result
foreach (char ch in str)
{
if(ch == ']') counter--;
if (counter > 0) // if we are inside brackets perform hide
{
if (ch == '[') result.Append('\uFFF0'); // add '\uFFF0' instead of '['
else if (ch == ']') result.Append('\uFFF1');
else if (ch == ';') result.Append('\uFFF2');
else result.Append(ch);
}
else result.Append(ch);
if (ch == '[') counter++;
}
string[] split = result.ToString().Split(separator); // Perform split. (characters are hidden now)
return split.Select(x => x
.Replace('\uFFF0', '[')
.Replace('\uFFF1', ']')
.Replace('\uFFF2', ';')).ToArray(); // unhide characters and give back result.
// dont forget: using System.Linq;
}
Some examples :
string[] a1 = HideSplit("AND[AND[Firstpart;Sndpart];sndpart]", bracket);
// Will give you this array { AND , AND[Firstpart;Sndpart];sndpart }
string[] a2 = HideSplit("AND[Firstpart;Sndpart];sndpart", semicolon);
// Will give you this array { AND[Firstpart;Sndpart] , sndpart }
string[] a3 = HideSplit("AND[Firstpart;Sndpart]", bracket);
// Will give you this array { AND , Firstpart;Sndpart }
string[] a4 = HideSplit("Firstpart;Sndpart", semicolon);
// Will give you this array { Firstpart , Sndpart }
And you can continue splitting this way.
Is there a way to tell c# to split by second semicolon?
There is no direct way to do that, but if that is precisely what you want, it's not hard to achieve:
string str="AND[AND[Firstpart;Sndpart];sndpart];
string[] tSplits = str.Split(';', 3);
string[] splits = { tSplits[0] + ";" + tSplits[1], tSplits[2] };
You could achieve the same result using a combination of IndexOf() and Substring(), however that is most likely not what you'll end up using as it's too specific and not very helpful for various inputs.
For your case, you need something that understands context.
In real-world complex cases you'd probably use a lexer / parser, but that seems like an overkill here.
Your best effort would probably be to use a loop, walk through all characters while counting +/- square brackets and spliting when you find a semicolon & the count is 1.
You can use Regex.Split, which is a more flexible form of String.Split:
string str = "AND[AND[Firstpart;Sndpart];sndpart]";
string[] arr = Regex.Split(str, #"(.*?;.*?;)");
foreach (var s in arr)
Console.WriteLine("'{0}'", s);
// output: ''
// 'AND[AND[Firstpart;Sndpart];'
// 'sndpart]'
Regex.Split splits not by chars, but by a string matching a regex expression, so it comes down to constructing a regex pattern meeting particular requirements. Splitting by a second semicolon is in practice splitting by a string that ends in a semicolon and that contains another semicolon before, so the matching pattern by which you split the input string could be for example: (.*?;.*?;).
The returned array has three elements instead of two because the splitting regex matches the beginning of the input string, in this case the empty string is returned as the first element.
You can read more on Regex.Split on msdn.

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

Categories