String to int array c

I am trying to get a string from the console and put all elements in an int array. It throws an error that my input was in a wrong format. I am trying with "1 1 3 1 2 2 0 0" and I need those as int values and later perform some calculations with them.

Here is my attempt:

7 Answers 7

You need to use String.Split Method to split your string with space ‘ ‘ in an array of strings and then convert each element to integer. You can iterate string array using System.Linq in efficient manner

Try changing it to this:

You are not splitting the string using space delimiter.

You cant try with "1 1 3 1 2 2 0 0", because it is trying to parse the spaces between the numbers. If you want your program to work you have to either make your input string like that: "11312200" or you can make a char array or just a single char if you dont have more than one separator where you assign and then .split the string by passing the separator, like that:

You can do this with a simple extension method:

If you don’t want to get an exception you can use this. It returns new int[] <0>when throw an exception.

Not the answer you’re looking for? Browse other questions tagged c# arrays or ask your own question.

Related

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Читайте также:  Как подключить двд к телевизору сони бравиа

site design / logo © 2020 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2020.1.17.35809

Given a string str containing numbers separated with “, “. The task is to convert it into an integer array and find the sum of that array.

Examples:

Recommended: Please try your approach on first, before moving on to the solution.

Approach:

  • Create an empty array with size as string length and initialize all of the elements of array to zero.
  • Start traversing the string.
  • Check if the character at the current index in the string is a comma(, ). If yes then, increment the index of the array to point to the next element of array.
  • Else, keep traversing the string until a ‘, ‘ operator is found and keep converting the characters to number and store at the current array element.
    To convert characters to number:

Below is the implementation of the above idea:

-2 Katy [2016-04-08 01:13:00]

Я работал над этим некоторое время, но я продолжаю получать <0,0,0,0,0>или <2751685, 2751685 и т.д.>Или

Я хочу ввести строку 12345 и получить ее так

предложения по моему коду?

c string arrays int

1 ответ

0 nalzok [2016-04-08 02:04:00]

Длина массива символов обычно не равна длине содержащейся в нем строки стиля С.

В качестве альтернативы добавьте

чтобы избежать потенциального доступа вне пределов доступа.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock detector