How to obtain an integer array from a string [duplicate] - c#

This question already has answers here:
Read numbers from the console given in a single line, separated by a space
(7 answers)
Split string, convert ToList<int>() in one line
(11 answers)
Closed 3 years ago.
I have gone through this solution. But this is not solving my problem. Let's say I have a string:
var aString = "0 -1 12 456 -512";
I want to convert this string to an int array like:
var convertedArray = [0, -1, 12, 456, -512];
How should I approach to solve this problem?

You can simply do this:
var stringNumbers = aString.Split(' ');
var numbers = new int[stringNumbers.Length];
for (int i = 0; i < stringNumbers.Length; i++)
numbers[i] = Convert.ToInt32(stringNumbers[i]);

var convertedArray = Array.ConvertAll(aString.Split(' '), int.Parse);

Related

why does this code throw exception with index out of range c# [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
I do not understand why this for loop is throwing exception. starting index is 0 and and index of inputStringArray is 4 so I really do not get it.
Console.WriteLine("please enter several numbers separated by hyphen");
var input = Console.ReadLine();
var inputStringArray = input.Split('-');
var listOfNumbers = new List<int>();
for (int i = 0; i < inputStringArray.Length; i++)
{
listOfNumbers[i] = Convert.ToInt32(inputStringArray[i]);
}
The problem is with the List, not with the array.
//listOfNumbers[i] = Convert.ToInt32(inputStringArray[i]);
listOfNumbers.Add(Convert.ToInt32(inputStringArray[i]));

Converting to double is changing my number C# 14.80 - > 1480 [duplicate]

This question already has answers here:
How to convert string to double with proper cultureinfo
(7 answers)
Closed 3 years ago.
I'm reading .txt file and spliting values into array like this:
for (int i = 0; i < articleItems.Length; i++)
{
List<string> splitStrings = articleItems[i].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
splitStrings[0] = splitStrings[0].Substring(12);
}
After that I'm trying to make object from those values, and everything is fine, but strange thing are happening here...
Here is the image from debugger, there is 14.80 at the beginning and when I convert that string to decimal it becomes 1480...:
Try
Double.Parse(splitStrings[2].ToString())

How to replace all items in an array of doubles with the same value [duplicate]

This question already has answers here:
How to populate/instantiate a C# array with a single value?
(26 answers)
Closed 6 years ago.
So lets say we have an array of doubles like this one that is later used for other stuff.
double[] myArray = new double[25];
How would I go about replacing all the values in that array with a set value?
There are flashier ways, but
for (int i = 0; i < myArray.Length; ++i){
myArray[i] = foo; /*the new value*/
}
is clear and simple.
The "flashy" way (simply create a new array):
var array = Enumerable.Repeat(value, count).ToArray();
Or
Array.ConvertAll(array, e => value);

Getting a substring 2 characters at a time [duplicate]

This question already has answers here:
Splitting a string / number every Nth Character / Number?
(17 answers)
Closed 8 years ago.
I have a string that looks something like:
0122031203
I want to be able to parse it and add the following into a list:
01
22
03
12
03
So, I need to get each 2 characters and extract them.
I tried this:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i=i+2) {
mList.Add(_CAUSE.Substring(i, _CAUSE.Length));
}
return mList;
but something is not right here, I keep getting the following:
Index and length must refer to a location within the string. Parameter
name: length
Did I get this wrong?
How about using Linq?
string s = "0122031203";
int i = 0;
var mList = s.GroupBy(_ => i++ / 2).Select(g => String.Join("", g)).ToList();
I believe you have may have specified the length incorrectly in the Substring function.
Try the following:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i = i + 2)
{
mList.Add(_CAUSE.Substring(i, 2));
}
return mList;
The length should be 2 if you wish to split this into chunks of 2 characters each.
when you do the substring, try _CAUSE.SubString(i, 2).
2points:
1) as previously mentioned, it should be substring(i,2);
2) U should consider the case when the length of ur string is odd. For example 01234: do u want it 01 23 and u'll discard the 4 or do u want it to be 01 23 4 ??

How to split a number into individual digits in c#? [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

Categories