在单行上给定的控制台,用空格隔开的数字阅读 [英] Read numbers from the console given in a single line, separated by a space

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

问题描述

我有任务在一行,从控制台空格隔开来读取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 。您可以提供您想要使用的字符串分割成多个字符(S)。如果你没有提供所有的空格被假定为分割字符(所以新线,标签等):

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天全站免登陆