从单行给出的控制台读取数字,用空格分隔 [英] Read numbers from the console given in a single line, separated by a space

查看:22
本文介绍了从单行给出的控制台读取数字,用空格分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是读取 单行中的 n 给定数字,由 空格 ( ) 从控制台.

I have a task to read n given numbers in a single line, separated by a space ( ) from the console.

当我读取 单独行 (Console.ReadLine()) 上的每个数字时,我知道该怎么做,但是当我遇到数字在同一行.

I know how to do it when I read every number on a separate line (Console.ReadLine()) but I need help with how to do it when the numbers are on the same line.

推荐答案

您可以使用String.Split.您可以提供要用于将字符串拆分为多个的字符.如果您没有提供所有 空白被假定为拆分字符(所以换行符、制表符等):

You can use String.Split. You can provide the character(s) that you want to use to split the string into multiple. If you provide none all white-spaces are assumed as split-characters(so new-line, tab etc):

string[] tokens = line.Split(); // all spaces, tab- and newline characters are used

或者,如果您只想使用空格作为分隔符:

or, if you want to use only spaces as delimiter:

string[] tokens = line.Split(' ');

如果你想将它们解析为 int 你可以使用 Array.ConvertAll():

If you want to parse them to int you can use Array.ConvertAll():

int[] numbers = Array.ConvertAll(tokens, int.Parse); // fails if the format is invalid

如果要检查格式是否有效,请使用 int.TryParse.

If you want to check if the format is valid use int.TryParse.

这篇关于从单行给出的控制台读取数字,用空格分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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