Convert string positions to integer

3
    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 that your put to convert the whole number ( Convert.ToInt32(numero) ) converts normally, but when converting only the positions, the program converts string to HTML code, according to the Unicode table, type, 2 = 50, 3 = 51 , all wrong. How do I convert each value from string to int ?

    
asked by anonymous 13.12.2018 / 01:20

3 answers

1

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

Read about char , which is nothing more than a 16-bit numeric value representing one character. To understand more about 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());
    
13.12.2018 / 02:13
3

The answers already posted break the application when a value that is not a number is typed, the correct thing is 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}");
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

    
17.12.2018 / 11:26
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 ();
        }
    }
}

Prevent your development including only tailoring to the end result.

    
13.12.2018 / 01:52