将字符串转换为C# [英] Converting string to sum C#

查看:74
本文介绍了将字符串转换为C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这一次,我以列表形式输入了数字,并用空格分隔了每个数字。现在,我编写的代码将数字按原样放置在一行中,但是当我尝试将字符串转换为Int32时,失败了,这杀死了程序并且没有给我总和。我对错误的理解还不是很清楚,无法准确解释出什么是错误。一个人如何将拆分后的字符串数组转换为数字以产生总和?

So this time, I've got numbers entered in as a list, with a space delimiting each number. The code I've written now places the number in a row as it should, but fails out when I try and convert the string to Int32, killing the program and not giving me the sum. I don't understand errors well enough yet to be able to decipher exactly what the error is. How does a guy convert split string arrays into numbers to produce a sum?

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

    namespace Dynamic_Entry
    {
    class Program
     {
    static void Main()
    {
        Console.Write("Please provide a list of numbers, separated by spaces: ");
        string list = Console.ReadLine();
        string[] parts = list.Split(' ');
        int sum = 0;

        for (int i = 0; i < parts.Length ; i++)
        {
            Console.WriteLine("{0, 5}", parts[i]);

        }

        sum = Convert.ToInt32(list);
        Console.WriteLine("-----");
        Console.Write("{0, 5}", sum);
        Console.ReadLine();

        }
      }
    }


推荐答案

for (int i = 0; i < parts.Length; i++)
{
    Console.WriteLine("{0, 5}", parts[i]);
    sum += Convert.ToInt32(parts[i]);
}

已固定。

您试图将 1 2 3 4 5 55转换为 int 。您必须将 1, 2, 3 ...转换为 int 并将它们添加到 sum

You were trying to convert "1 2 3 4 5 55" to an int. You must convert "1", "2, "3"... to an int and add them to sum.

我要补充一点,如果您想分割字符串,最好做类似

I'll add that if you want to Split the string, it would be better to do something like

string[] parts = list.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

通过这种方式,数字之间的多个空格将被删除(例如1     2 3)

In this way multiple spaces between numbers are removed (1     2 3 for example)

Andrei发布了一个使用LINQ的非常简单的示例...

Andrei had posted a very simple example of use of LINQ...

int sum = parts.Sum(p => Convert.ToInt32(p));

这会超出 for 周期。它将转换为 int 并添加所有部分。这意味着对于每个部分将其转换为 int 并添加。返回总和。

This you would put OUTSIDE the for cycle. It converts to int and adds all the "parts". It means "for each part convert it to int and add it. Return the sum".

这篇关于将字符串转换为C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆