简体   繁体   English

如何在空格字符上拆分一串数字并转换为整数

[英]How to split a string of numbers on the white space character and convert to integers

I'm working on some homework and I need to get an input from the user which is a single line of numbers separated by spaces. 我正在做一些功课,我需要从用户那里获得一个由空格分隔的单行数字输入。 I want to split this string and get the individual numbers out so that I can insert them into a Binary Search Tree. 我想拆分这个字符串并获取各个数字,以便我可以将它们插入二进制搜索树。

I tried the split function and was able to rid of the white space but I'm not sure how to "collect" the individual numbers. 我尝试了拆分功能,并且能够摆脱空白区域,但我不确定如何“收集”个别数字。

        string data;
        string[] newdata = { };
        Console.WriteLine("Please enter a list of integers with spaces 
                           between each number.\n");
        data = Console.ReadLine();
        newdata = data.Split(null);

        Console.WriteLine(String.Join(Environment.NewLine, newdata));

I want to somehow collect the elements from newdata string array and convert them into integers but I'm having a tough time figuring out how to do that. 我想以某种方式从newdata字符串数组中收集元素并将它们转换为整数,但我很难搞清楚如何做到这一点。

Well, you could use Linq .Select method combined with .Split method: 好吧,你可以使用Linq .Select方法结合.Split方法:

List<int> newData = data.Split(' ').Select(int.Parse).ToList();

If you want user to be able to enter empty spaces we need to trim the resulting strings after split. 如果您希望用户能够输入空格,我们需要在拆分后修剪生成的字符串。 For that we can use another overload of string.Split method that accepts StringSplitOptions : 为此,我们可以使用另一个接受StringSplitOptionsstring.Split方法的重载:

List<int> newData = data.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();

Finally if you want to allow user to enter incorrect data at times and still get collection of valid ints you could use int.TryParse and filter out values that were parsed incorrectly: 最后,如果您希望允许用户有时输入不正确的数据并仍然获得有效的整数,您可以使用int.TryParse并过滤掉错误解析的值:

List<int> newData = data.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => int.TryParse(s.Trim(), out var n) ? (int?)n : null)
                        .Where(x => x != null)
                        .Select(i => i.Value)
                        .ToList();

OK as code: 好的代码:

var words = data.Split();
int i;
List<int> integers = new List<int>();
foreach(var s in words)
{
  if (int.TryParse(s, out i)) {integers.Add(i);}
}
// now you have a list of integers
// if using decimal, use decimal instead of integer

Some smart LINQ answers are already provided, here is my extended step by step solution which also allows to ignore invalid numbers: 已经提供了一些聪明的LINQ答案,这是我的扩展一步一步的解决方案,它也允许忽略无效的数字:

//Read input string
Console.Write("Input numbers separated by space: ");
string inputString = Console.ReadLine();
//Split by spaces
string[] splittedInput = inputString.Split(' ');
//Create a list to store all valid numbers
List<int> validNumbers = new List<int>();
//Iterate all splitted parts
foreach (string input in splittedInput)
{
    //Try to parse the splitted part
    if (int.TryParse(input, out int number) == true)
    {
        //Add the valid number
        validNumbers.Add(number);
    }
}
//Print all valid numbers
Console.WriteLine(string.Join(", ", validNumbers));

You can do as follows. 你可以这样做。

var numbers = Console.ReadLine();
var listOfNumbers = numbers.Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries)
                           .Select(x=> Int32.Parse(x));

The above lines split the user input based on "whitespace", removing any empty entries in between, and then converts the string numbers to integers. 上面的行基于“空格”拆分用户输入,删除其间的任何空条目,然后将字符串数转换为整数。

The StringSplitOptions.RemoveEmptyEntries ensures that empty entries are removed. StringSplitOptions.RemoveEmptyEntries确保删除空条目。 An example of empty entry would be an string where two delimiters occur next to each other. 空条目的示例是一个字符串,其中两个分隔符彼此相邻。 For example, "2 3 4 5" , there are two whitespaces between 2 and 3,which means, when you are spliting the string with whitespace as delimiter, you end up with an empty element in array. 例如, "2 3 4 5" ,在2和3之间有两个空格,这意味着,当您使用空格作为分隔符拆分字符串时,最终会在数组中使用空元素。 This is eliminated by usage of StringSplitOptions.RemoveEmptyEntries 这可以通过使用StringSplitOptions.RemoveEmptyEntries来消除

Depending on whether you are expecting Integers or Decimals, you can use Int32.Parse or Double.Parse (or float/decimal etc) 根据您是否期望整数或小数,您可以使用Int32.ParseDouble.Parse (或浮点/小数等)

Furthermore, you can include checks to ensure you have a valid number, otherwise throw an exception. 此外,您可以包含检查以确保您具有有效数字,否则抛出异常。 You can alter the query as follows. 您可以按如下方式更改查询。

var listOfNumbers = numbers.Split(new[]{" "},StringSplitOptions.RemoveEmptyEntries)
                   .Select(x=> 
                    {
                        Console.WriteLine(x);
                        if(Int32.TryParse(x,out var number))
                            return number;
                        else
                            throw new Exception("Element is not a number");
                    });

This ensures all the element in the list are valid numbers, otherwise throw an exception. 这可以确保列表中的所有元素都是有效数字,否则会抛出异常。

保留空格并使用空格“data.split('');”进行“拆分”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM