Question

I want to add up all numbers in a string,
I am sure this can be done easy with a for loop.
I have:

int numbers = 1234512345;

for (int i = 0 ; i numbers.Length ; i++)        
{            
    int total;            
    total = int [i];
}

But it won't work for a reason, I am puzzled a lot.

Était-ce utile?

La solution

For one, the "string" you're trying to iterate over is an int. You probably meant something along the lines of

string numbers = "1234512345"

After that, there are several ways to do this, my favorite personally is iterating over each character of the string, using a TryParse on it (this eliminates any issues if the string happens to be alphanumeric) and totaling the result. See below:

    static void Main(string[] args) {
        string numbers = "1234512345";
        int total = 0;
        int num; // out result

        for (int i = 0; i < numbers.Length; i++) {
            int.TryParse(numbers[i].ToString(), out num);
            total += num; // will equal 30
        }
        Console.WriteLine(total);

        total = 0;
        string alphanumeric = "1@23451!23cf47c";
        for (int i = 0; i < alphanumeric.Length; i++) {
            int.TryParse(alphanumeric[i].ToString(), out num);
            total += num; // will equal 32, non-numeric characters are ignored
        }
        Console.WriteLine(total);

        Console.ReadLine();
    }

Like others have posted though, there are several ways to go about this, it's about personal preference most of all.

Autres conseils

this should do what you want

int total = 0;
foreach(char numchar in numbers)
{
     total += (int)char.GetNumericValue(numchar);
}

EDIT:

1 line solution:

 int total = numbers.Sum(x=> (int)char.GetNumericValue(x));

PS: Why the downvotes?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top