Convert string to integer positions

Asked

Viewed 551 times

2

    Console.Write("Digite um numero de 4 digitos: ");
    string numero = Convert.ToString(Console.ReadLine());
    int soma = 0;

    for(int i = 0; i < numero.Length; i++)
    {
        soma += Convert.ToInt32(numero[i]);
    }
    Console.WriteLine("Soma dos numeros = "+soma);

I know your put to convert the whole number (Convert.ToInt32(numero)) converts normally, but when converting only the positions, the program converts the string for HTML code, according to Unicode table, type, 2 = 50, 3 = 51, all wrong. How do I convert each value of string for int?

3 answers

2

Already posted answers break the application when a value that is not a number is typed, it is correct to do this:

using static System.Console;

public class Program {
    public static void Main() {
        Write("Digite um numero de 4 digitos: ");
        var numero = ReadLine();
        var soma = 0;
        foreach (var chr in numero) {
            if (!char.IsDigit(chr)) {
                WriteLine("não é um número válido");
                return;
            }
            soma += chr - '0';
        }
        WriteLine($"Soma dos numeros = {soma}");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

0

Using Linq and Generic you can do this in a simple way:

using System;
using System.Collections.Generic;
using System.Linq;

namespace valor_posicao_string {
    class Program {
        static void Main (string[] args) {
            Console.Write ("Digite um numero de 4 digitos: ");
            string numero = Console.ReadLine ();
            IEnumerable<int> digits = numero.Select (x => int.Parse (x.ToString ()));
            Console.WriteLine ("Soma dos numeros = " + digits.Sum());
            Console.ReadKey ();
        }
    }
}

I prevented its development by including only adaptation to the final result.

  • I know, bro, you can do it in a lot of ways, but it’s not even about adding up the string values. The question that arose for me was the question of not being able to convert an index from a string to an integer. I want to know just that, how to convert, for example the string number = 2345, number[0] = 2, and take that number [0] and convert to integer, which I don’t know how, I’m looking up so far. if I convert using Convert.Toint32(number[0]), in this case it was supposed to give 2, but 50.

  • Actually the index itself is already separated and is an integer. The conversion is already happening in Lambda. The "digits" object is a list of integers. In your example 2345 the object is 2,3,4,5 (list of integers).

0


One string is a array of char. So when you access the numero[i] you are accessing a value of type char.

Read about char, which is nothing more than a 16-bit numeric value representing a character. To better understand what value each character represents, study the ascii table.

To get the result you expect, turn your char into string, like this:

soma += Convert.ToInt32(numero[i].ToString());
  • thanks...I already got what I wanted. That’s right, a string is an array of char, so I wasn’t sure how to do it. When I put Convert.Toint32(number[0]), I was just representing the char in integer form, (actually the char is a noun) so I gave the corresponding number to the ASCII table. I did the following. I put sum+= (int)(number[i] - '0') and it worked. cahr '0' = 48 in the table, 1 = 49, 2 = 50.... just subtract the '0' and it’s gone, vlw by the answer.

  • Glad you helped @pauloestevão, if you feel that this answer is the most appropriate for your problem you can mark it as accepted. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.