How to split a string by an empty string delimiter [duplicate] - c#

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();

Related

Convert special character in string into a char

I have this string:
string specialCharacterString = #"\n";
where "\n" is the new line special character.
Is it possible convert/assign that string (of two characters) into a (single) char. How do I do something like:
char specialCharacter = Parse(specialCharacterString);
Where specialCharacter value would be equal to \n
Is there anything in dotnet that would parse the string for me or must I use if or switch the string (the string can contain any special character) to accomplish what I want. Note that char.Parse(string) cannot handle special characters and thinks the string above is actually two characters.
Maybe I am oversimplifying but can't you just do the following:
txtString.Replace("\n", "$");
It is technically a string to string replacement but would be string to char...
You can always cast it to a char since you know what char you are replacing the string with.
Not sure, what business need it is, but if you need parsing C# in C# you can use some tools like Antlr, which supports C# grammar (https://github.com/antlr/grammars-v4/)
I don't think there is any ready tool designed just for strings
Try use Regex.Unescape(specialCharacterString);
It will return the new string with escape characters.
For example:
var literalStringWithEscapeCharacters = #"Hello\tWorld";
var stringWithEscapeCharacters = Regex.Unescape(literalStringWithEscapeCharacters);
Console.WriteLine(stringWithEscapeCharacters);
Will print: Hello World
Instead of: Hello\tWorld
Then you can find escape characters in stringWithEscapeCharacters like this:
var escapeChars= new [] { '\n' };
var characters = stringWithEscapeCharacters.Where(c => escapeChars.Contains(c)).ToList();
All escape characters described here:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-escape-sequences

How can I use String.Split with a String delimiter?

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.

Confusing error when splitting a string

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

Please tell me what the problem is c# regex.split()

string temp_constraint = row["Constraint_Name"].ToString();
string split_string = "FK_"+tableName+"_";
string[] words = Regex.Split(temp_constraint, split_string);
I am trying to split a string using another string.
temp_constraint = FK_ss_foo_ss_fee
split_string = FK_ss_foo_
but it returns a single dimension array with the same string as in temp_constraint
Please help
Your split operation works fine for me:
string temp_constraint = "FK_ss_foo_ss_fee";
string split_string = "FK_ss_foo_";
string[] words = Regex.Split(temp_constraint, split_string);
foreach (string word in words)
{
Console.WriteLine(">{0}<", word);
}
Output:
><
>ss_fee<
I think the problem is that your variables are not set to what you think they are. You will need to debug to find the error elsewhere in your program.
I would also avoid using Split for this (both Regex and String.Split). You aren't really splitting the input - you are removing a string from the start. Split might not always do what you want. Imagine if you have a foreign key like the following:
FK_ss_foo_ss_fee_FK_ss_foo_ss_bee
You want to get ss_fee_FK_ss_foo_ss_bee but split would give you ss_fee_ and ss_bee. This is a contrived example, but it does demonstrate that what you are doing is not a split.
You should use String.Split instead
string[] words =
temp_constraint.Split(new []{split_string}, StringSplitOptions.None);
string split uses a character array to split text and does the split by each character which is not often ideal.
The following article shows how to split text by an entire word
http://www.bytechaser.com/en/functions/ufgr7wkpwf/split-text-by-words-and-not-character-arrays.aspx

how to split a string by another 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.

Categories