c#(泛型类 有一个 数组 ) 根据输入内容是否是数字 存储到不同的数组中
时间: 2023-11-28 16:49:32 浏览: 54
可以使用泛型类以及C#自带的IsDigit()方法来实现。以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int>();
List<string> strings = new List<string>();
Console.WriteLine("Please enter a series of numbers or strings separated by commas:");
string input = Console.ReadLine();
string[] inputArray = input.Split(',');
foreach (string item in inputArray)
{
if (IsNumeric(item))
{
numbers.Add(int.Parse(item));
}
else
{
strings.Add(item);
}
}
Console.WriteLine("Numbers:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Console.WriteLine("Strings:");
foreach (string str in strings)
{
Console.WriteLine(str);
}
Console.ReadLine();
}
public static bool IsNumeric(string input)
{
return int.TryParse(input, out int n);
}
}
```
在这个示例中,我们首先创建了两个空的泛型列表 `numbers` 和 `strings`,用于存储数字和非数字的输入内容。然后读取用户输入的字符串,并使用 `Split()` 方法将其分成一个字符串数组。
接下来,使用 `foreach` 循环遍历数组中的每个元素,并使用 `IsNumeric()` 方法确定该元素是否为数字。如果是数字,则将其转换为整数,并将其添加到 `numbers` 列表中。如果不是数字,则将其添加到 `strings` 列表中。
最后,我们使用 `foreach` 循环遍历 `numbers` 和 `strings` 列表,并将它们分别打印出来。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)