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.
这篇关于从单行给出的控制台读取数字,用空格分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从单行给出的控制台读取数字,用空格分隔
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
