Cannot convert string[] to char[] - c#

I have a textbox (textBoxA), I would do a split of the content, being single letters would put them in a char[] array (I will not use the lists). Here is the code I used, where I'm wrong?
char[] but = textBoxA.Text.Split("-".ToCharArray());

If you don't mind the iteration, use Linq :) (using System.Linq;)
char[] but = textBoxA.Text.Split('-').Select(s => Convert.ToChar(s)).ToArray();

Consider what you are doing. String.Split returns an array of Strings (string[]). If you assume that your input will only be individual characters, then you can use:
char[] values = textBoxA.Text.Split(new [] { '-' }, StringSplitOptions.RemoveEmptyEntries).Select(e => e[0]).ToArray( );

Array of string will be returned. See
string[] but = textBoxA.Text.Split("-".ToCharArray());
Also,
string[] but = textBoxA.Text.Split('-');

Splitreturns a string array. If you want a char array with each of the strings in order, you have to loop to the array returned by Split, convert each string individually and Append (or Add, can't recall the correct syntax), the char array that results from the conversion to your destination array.

You can also use..
string s = "A-B-C-D-E";
char[] but = s.Split('-').Select(Convert.ToChar).ToArray();
...which is slightly shorter that one of the answers.

Related

Split string and exclude last split

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

How to remove Whitespce from stringArray formed based on whitespace

I have a string which contains value like.
90 524 000 1234567890 2207 1926 00:34 02:40 S
Now i have broken this string into string Array based on white-space.Now i want to create one more string array into such a way so that all the white-space gets removed and it contains only real value.
Also i want to get the position of the string array element from the original string array based on the selection from the new string array formed by removing white space.
Please help me.
You can use StringSplitOptions.RemoveEmptyEntries via String.Split.
var values = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries: The return value does not include array elements that contain an empty string
When the Split method encounters two consecutive white-space it will return an empty string.Using StringSplitOptions.RemoveEmptyEntries will remove the empty strings and give you only the values you want.
You can also achieve this using LINQ
var values = input.Split().Where(x => x != string.Empty).ToArray();
Edit: If I understand you correctly you want the positions of the values in your old array. If so you can do this by creating a dictionary where the keys are the actual values and the values are indexes:
var oldValues = input.Split(' ');
var values = input.Split().Where(x => x != string.Empty).ToArray();
var indexes = values.ToDictionary(x => x, x => Array.IndexOf(oldValues, x));
Then indexes["1234567890"] will give you the position of 1234567890 in the first array.
You can use StringSplitOptions.RemoveEmptyEntries:
string[] arr = str.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
Note that i've also added tab character as delimiter. There are other white-space characters like the line separator character, add as desired. Full list here.
string s = "90 524 000 1234567890 2207 1926 00:34 02:40 S ";
s.Split(' ').Where(x=>!String.IsNullOrWhiteSpace(x))

Split a string on the Empty Character literal. Break apart a string's symbols into an array

i have the following string =
"00101010"
and i need the following array/list:
var.ElementAt(0) = "0"
var.ElementAt(1) = "0"
var.ElementAt(2) = "1"
var.ElementAt(3) = "0"
var.ElementAt(4) = "1"
var.ElementAt(5) = "0"
var.ElementAt(6) = "1"
var.ElementAt(7) = "0"
if i try string.split('') the compiler complains about a empty character literal.
Thanks for any help.
You can use Linq:
var chars = "00101010".Select(c => c.ToString()).ToArray();
This should do it:
string mys = "hello";
char[] thechars = mys.ToCharArray();
Use ToCharArray. But the more pertinent question is what you need to do with your result since string already implements IEnumerable<char> allowing you to iterate and do whatever you need with the characters in the string.
If you want to get a specific character in a string, just index the string; there is no need to convert it to an array of anything:
var s = "0123";
var c = s[0]; // -> '0'
If you really need strings and not chars, then Tim's answer will work.
There is a one line reg-ex solution that returns string[] instead of char[]:
var arr = Regex.Split(s, "(?<=.)(?=.)");
It'd be interesting if there's a one line non-Linq solution or a shorter correct reg-ex.
Note: I'd have posted under the other reg-ex answer but it seems to have been deleted due to missing # string prefix and it's limitation to only splitting digits.

splitting string into array with a specific number of elements, c#

I have a string which consists number of ordered terms separated by lines (\n) as it shown in the following example: (note, the string I have is an element of an array of string)
term 1
term 2
.......
.......
term n
I want to split a specific number of terms, let we say (1000) only and discard the rest of the terms. I'm trying the following code :
string[] training = traindocs[tr].Trim().Split('\n');
List <string> trainterms = new List<string>();
for (int i = 0; i < 1000; i++)
{
if (i >= training.Length)
break;
trainterms.Add(training[i].Trim().Split('\t')[0]);
}
Can I conduct this operation without using List or any other data structure? I mean just extract the specific number of the terms into the the Array (training) directly ?? thanks in advance.
How about LINQ? The .Take() extension method kind of seems to fit your bill:
List<string> trainterms = traindocs[tr].Trim().Split('\n').Take(1000).ToList();
According to MSDN you can use an overloaded version of the split method.
public string[] Split( char[] separator, int count,
StringSplitOptions options )
Parameters
separator Type: System.Char[] An array of Unicode characters that
delimit the substrings in this string, an empty array that contains no
delimiters, or null.
count Type: System.Int32 The maximum number of
substrings to return.
options Type: System.StringSplitOptions
StringSplitOptions.RemoveEmptyEntries to omit empty array elements
from the array returned; or StringSplitOptions.None to include empty
array elements in the array returned.
Return Value
Type: System.String[] An array whose elements contain the substrings
in this string that are delimited by one or more characters in
separator. For more information, see the Remarks section.
So something like so:
String str = "A,B,C,D,E,F,G,H,I";
String[] str2 = str.Split(new Char[]{','}, 5, StringSplitOptions.RemoveEmptyEntries);
System.Console.WriteLine(str2.Length);
System.Console.Read();
Would print: 5
EDIT:
Upon further investigation it seems that the count parameter just instructs when the splitting stops. The rest of the string will be kept in the last element.
So, the code above, would yield the following result:[0] = A, [1] = B, [2] = C, [3] = D, [4] = E,F,G,H,I, which is not something you seem to be after.
To fix this, you would need to do something like so:
String str = "A\nB\nC\nD\nE\nF\nG\nH\nI";
List<String> myList = str.Split(new Char[]{'\n'}, 5, StringSplitOptions.RemoveEmptyEntries).ToList<String>();
myList[myList.Count - 1] = myList[myList.Count - 1].Split(new Char[] { '\n' })[0];
System.Console.WriteLine(myList.Count);
foreach (String str1 in myList)
{
System.Console.WriteLine(str1);
}
System.Console.Read();
The code above will only retain the first 5 (in your case, 1000) elements. Thus, I think that Darin's solution might be cleaner, if you will.
If you want most efficient(fastest) way, you have to use overload of String.Split, passing total number of items required.
If you want easy way, use LINQ.

Substring of a variant string

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.

Categories