Am looking for the code which need to convert string to int array so far what i done is :
string text = "[1,2]";
int[] ia = text.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
But am getting number format exception how to get rid of this here is the string "[1,2]" need to convert into [1,2] how can i achieve this it may be dumb question but need to solve this.
Just a piece of cake using JsonConvert,
int[] arr = JsonConvert.DeserializeObject<int[]>(text);
Just Trim the string's '[' and ']' and split by ',' to get it as array.
Then convert it to int array using 'Array.ConvertAll' method.
string s = "[1,2]";
string[] s1 = s.Trim('[', ']').Split(',');
int[] myArr = Array.ConvertAll(s1, n => int.Parse(n));
Replace the braces [] with empty string and then apply Split function.
objModellead.ServiceCatalogID
.Replace("[","")
.Replace("]","")
.Split(';')
.Select(int.Parse)
.ToArray()
Related
I am new to C#. I am trying to declare a char array that contains few string values. Trying to use the ToCharArray() method to copy the string to a char array it return character array of a string. However, I get the error saying it cannot implicitly convert char[] to char.
Here's the code I have written:
char[] country= new char[5];
country[1] = "japan".ToCharArray();
country[2] = "korea".ToCharArray();
It works when I write it like this:
char[] country= "japan".ToCharArray();
but I want to use it in an array so I can randomize and choose an element from any of 5 values assigned. I would really appreciate if anyone could help, thanks.
I believe you try to have array of char arrays:
char[][] countries = new char[5][];
countries[1] = "japan".ToCharArray();
countries[2] = "korea".ToCharArray();
Every element in the array is one character.
So country[0] is "j", country[1] is "a" and so on.
with
country[1] = "japan".ToCharArray();
you try to put an array into a char, and give you an error.
Perhaps you want a list of chars. So you can use an array of array or a list of country.
for the first country for example
List<string> country = new List<string>() {
"japan",
"korea"
};
var random = new Random();
var character = country[0][random.Next(0, country[0].Length)];
I am trying to parse a string into array and find a very concise approach.
string line = "[1, 2, 3]";
string[] input = line.Substring(1, line.Length - 2).Split();
int[] num = input.Skip(2)
.Select(y => int.Parse(y))
.ToArray();
I tried remove Skip(2) and I cannot get the array because of non-int string. My question is that what is the execution order of those LINQ function. How many times is Skip called here?
Thanks in advance.
The order is the order that you specify. So input.Skip(2) skips the first two strings in the array, so only the last remains which is 3. That can be parsed to an int. If you remove the Skip(2) you are trying to parse all of them. That doesn't work because the commas are still there. You have splitted by white-spaces but not removed the commas.
You could use line.Trim('[', ']').Split(','); and int.TryParse:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int i = 0;
int[] num = input.Where(s => int.TryParse(s, out i)) // you could use s.Trim but the spaces don't hurt
.Select(s => i)
.ToArray();
Just to clarify, i have used int.TryParse only to make sure that you don't get an exception if the input contains invalid data. It doesn't fix anything. It would also work with int.Parse.
Update: as has been proved by Eric Lippert in the comment section using int.TryParse in a LINQ query can be harmful. So it's better to use a helper method that encapsulates int.TryParse and returns a Nullable<int>. So an extension like this:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Now you can use it in a LINQ query in this way:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int[] num = input.Select(s => s.TryGetInt32())
.Where(n => n.HasValue)
.Select(n=> n.Value)
.ToArray();
The reason it does not work unless you skip the first two lines is that these lines have commas after ints. Your input looks like this:
"1," "2," "3"
Only the last entry can be parsed as an int; the initial two will produce an exception.
Passing comma and space as separators to Split will fix the problem:
string[] input = line
.Substring(1, line.Length - 2)
.Split(new[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
Note the use of StringSplitOptions.RemoveEmptyEntries to remove empty strings caused by both comma and space being used between entries.
I think it would be better you do it this way:
JsonConvert.DeserializeObject(line, typeof(List<int>));
you might try
string line = "[1,2,3]";
IEnumerable<int> intValues = from i in line.Split(',')
select Convert.ToInt32(i.Trim('[', ' ', ']'));
i have a string variable which receives data from web the data is in the from of string like this
string output="[1,2,3,4,5,6,7,8,9,0]";
i want to convert it into a string array [] so that i can specify each element via for each loop
string output;
into
string[] out;
PS: if any predefined method is there that will also help
You can do that using Trim And Split:
var out = output.TrimStart('[').TrimEnd(']').Split(',');
But your data looks like JSON string. So, if you are dealing with JSON instead of making your own parser try using libraries that already does that such as JSON.NET.
You can use Trim functions to remove brackets and then use Split() function to get the string array that contains the substrings in this string that are delimited by elements of a specified Unicode character.
var res = output.TrimStart('[')
.TrimEnd(']')
.Split(',');
string[] arr = output.Where(c => Char.IsDigit(c)).Select(c => c.ToString()).ToArray();
output.Substring(1, output.Length - 2).Split(',');
I have a short[] Numbers;
Now I want to convert the numbers in the array into a string with each array value separated by a comma. How do I do this in C#?
short[] Numbers = {1, 2, 3, 4};
I want this as a string "1,2,3,4" to store in the database.
PS: I checked many questions in SO for the same topic but did not get exact match. Hence I am asking this one
Try the following
string result = String.Join(",", Numbers);
Note: this won't work in 3.5 or earlier because String.Join lacks the necessary overloads. To use this API the code would need to change to
string result = String.Join(",", Numbers.Select(x => x.ToString()).ToArray());
String result = string.Join(",", Numbers);
It can be done using LINQ -
string result = String.Join(",", Numbers.Select(p=>p.ToString()).ToArray());
EDIT -
string result = String.Join(",", Numbers);
As pointed out by Jean Hominal below, the Select and the ToArray can be removed due to the String.Join<T>(String, IEnumerable<T>) overload.
Is there any way to convert a string ("abcdef") to an array of string containing its character (["a","b","c","d","e","f"]) without using the String.Split function?
So you want an array of string, one char each:
string s = "abcdef";
string[] a = s.Select(c => c.ToString()).ToArray();
This works because string implements IEnumerable<char>. So Select(c => c.ToString()) projects each char in the string to a string representing that char and ToArray enumerates the projection and converts the result to an array of string.
If you're using an older version of C#:
string s = "abcdef";
string[] a = new string[s.Length];
for(int i = 0; i < s.Length; i++) {
a[i] = s[i].ToString();
}
Yes.
"abcdef".ToCharArray();
You could use linq and do:
string value = "abcdef";
string[] letters = value.Select(c => c.ToString()).ToArray();
This would get you an array of strings instead of an array of chars.
Why don't you just
string value="abcd";
value.ToCharArray();
textbox1.Text=Convert.toString(value[0]);
to show the first letter of the string; that would be 'a' in this case.
Bit more bulk than those above but i don't see any simple one liner for this.
List<string> results = new List<string>;
foreach(Char c in "abcdef".ToCharArray())
{
results.add(c.ToString());
}
results.ToArray(); <-- done
What's wrong with string.split???