Read numbers from the console given in a single line, separated by a space(从单行给出的控制台读取数字,用空格分隔)
问题描述
我的任务是读取 单行中的 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
.
这篇关于从单行给出的控制台读取数字,用空格分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从单行给出的控制台读取数字,用空格分隔


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04