I have string like so:
"ABCDEF--Split--GHIKLMO--Split--PQRSTUVWXYZ"
what I am trying to do is split this string with --Split-- being the delimiter, I have obviously tried the following:
var array = item.split('--Split--');
but I get this error:
Too many characters in character literal
Is there away to do this?
The problem with your above code is that you are trying to pass in a string as a char instead of using the correct overload:
item.Split(new []{"--Split--"}, StringSplitOptions.None)
MSDN Documentation
You're using the string.Split that uses CHAR as parameter. See that single quote are used to create char type in C#.
You have to use the overload that receives an string array as parameter.
item.split(new string[]{"--Split--"},StringSplitOptions.RemoveEmptyEntries);
The first parameter is an array of strings that you want to split.
The second parameter, the StringSplitOptions has two possible values:
None (will split also empty values), the example below will give you an string array with three elements. The first will be "This is an string test", second wil lbe "I will split by ", and third will be "":
var test = "This is an string test, I will split by ,";
var splittedStrings = test.Split(",", StringSplitOptions.None);
RemoveEmptyEntries, this will remove the empty entries of splitted string. If you take the example above using the RemoveEmptyEntries you will have an array with only two values: "This is an string test" and "I will split by ". The empty string at final will be cutted of.
Related
I am not as familiar with RegEx as I probably should be.
However, I am looking for an expression(s) that matches a variant of values.
My string:
2020/09/10 05:41:02,ABC,888,!"#$%'()=~|{`}*+_?><-^\#[;:]./\,{"data1-1":"48.16","data1-2":"!"#$%'()=~|{`}*+_?><-^\#[;:]./\"}
I am trying to split comma using regular expression to get the result below:
string regex = "," + #"\s*(?![^{}]*\})";
List listResult = Regex.Split(myString, regex).ToList();
The received results are not correct.
Can regular expressions be used in this case?
What could i use to split that string according to every comma outside the { }? Cheers
I'm not sure how this works with regular expressions. However, instead of using regex, you could just create a list with your delimiters and use the string.split method:
char[] delim = new [] {','}; //in your case just one delimiter
var listResult = myString.Split(delim, StringSplitOptions.RemoveEmptyEntries);
The string.split method returns an array.
You can check how comma separated value format (CSV) is usually parsed.
Here with a regex : https://stackoverflow.com/a/18147076/6424355
Split using comma is simpler if you don't needs quotes
This question already has answers here:
Best way to specify whitespace in a String.Split operation
(11 answers)
Closed 4 years ago.
In java,
String.split("");
is possible.
ex)
String[] str = "Hello world!".split("")
Like this, I want to split String without escape sequence.
But in C#, I tried it and IDE said 'Error'. Is there any solution?
edit)
Code:
String[] str = "Hello world!".split("");
the result is str[0] = H, str[1] = e, ...(in java)
In C#, I tried
strI[i] = "Hello World!".Split('');
And the result is
'error CS1011: Empty character literal
I want to split string with Empty literal.
Please note that no overloaded methods of String.Split() accepts a string as first argument like what you used. Following are the possible overloaded methods
The thing you are looking for is to split a string into characters. For that you can depend on String.ToCharArray Method, which will Copies the characters in this instance to a Unicode character array.:
char[] charArray = "Hello world!".ToCharArray();
So that we can access each characters using its index, that means - charArray[0] will be H.
If you need the splitted characters into a string array means you can use something like this:
string[] strArray = "Hello world!".Select(x=> x.ToString())
.ToArray();
The reason you are getting an error is because there is no method with the signature matching your call. In other words, when you call Split method, you must pass the first parameter as a character array or string array, whereas you are passing the first argument as simply a string.
Following call would not throw any error since it matches the signature of Split method.
string[] sArray = s.Split(new string[] {""}, StringSplitOptions.None);
However, above method will result in nothing productive since the resulting array will contain only one element whose value will be original string.
If your goal was to split a string into individual characters then you can use code like below.
string s = "some string";
var splitString = s.ToCharArray();
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 have this line of code:
string[] ids = Request.Params["service"].Split(",");
the values in Request.Params["service"] are: "1,2"
Why am I getting:
Error 1 The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'char[]'
This makes no sense to me....
The error happens on everything to the right of the equal sign
You need to pass a character (System.Char), not a string:
string[] ids = Request.Params["service"].Split(',');
There is no overload to String.Split that takes a params string[] or a single string, which is what would be required to make your code work.
If you wanted to split with a string (or multiple strings), you would need to use a string[] and specify splitting options:
string[] ids = Request.Params["service"].Split(new[]{","}, StringSplitOptions.None);
You have to use the overload with the params Char[]:
string[] ids = Request.Params["service"].Split(',');
As others said on here your provided (",") the double quote denotes a string and the Split function accepts a Character array or char[]. Use (',') , the single quote denotes a character. You can also pass along StringSplitOptions which if you happen to get empty values in your string[] it requires a char[] to be passed along with it, illustrated below.
string splitMe = "test1,test2,";
string[] splitted1 = splitMe.Split(',');
string[] splitted2 = splitMe.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
//Will be length 3 due to extra comma
MessageBox.Show(splitted1.Length.ToString());
//Will be length 2, Removed the empty entry since there was nothing after the comma
MessageBox.Show(splitted2.Length.ToString());
In the line
Request.Params["service"].Split(",");
You're splitting by "," instead of ','
The .Split() method takes an array of characters, not a string
I have a string in following format
"TestString 1 <^> TestString 2 <^> Test String3
Which i want to split by "<^>" string.
Using following statement it gives the output i want
"TestString 1 <^> TestString 2 <^> Test String3"
.Split("<^>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
But if my string contains "<" , ">" or "^" anywhere in the text then above split statement will consider that as well
Any idea how to split only for "<^>" string ?
By using ToCharArray you are saying "split on any of these characters"; to split on the sequence "<^>" you must use the overload that accepts a string[]:
string[] parts = yourValue.Split(new string[]{"<^>"}, StringSplitOptions.None);
Or in C# 3:
string[] parts = yourValue.Split(new[]{"<^>"}, StringSplitOptions.None);
Edit: As others pointed already out: String.Split has a good overload for your usecase. The answer below is still correct (as in working), but - not the way to go.
That's because this string.Split overload takes an array of separator chars. Each of them splits the string.
You want: Regex.Split
Regex regex = new Regex(#"<\^>");
string[] substrings = regex.Split("TestString 1 <^> TestString 2 <^> Test String3");
And - a sidenote:
"<^>".ToCharArray()
is really just a fancy way to say
new[]{'<', '^', '>'}
Try another overloaded Split method:
public string[] Split(
string[] separator,
StringSplitOptions options
)
So in you case it may looks like:
var result =
yourString.Split(new string[] {"<^>"},StringSplitOptions.RemoveEmptyEntries);
Hope, this helps.