给我一个csharp函数,要求能够从字符串中提取其中的数字并存储在一个局部变量内
时间: 2024-05-16 21:15:40 浏览: 19
以下是一个可以从字符串中提取数字的 C# 函数示例:
```csharp
public void ExtractNumbers(string input)
{
string numbers = string.Empty;
foreach (char c in input)
{
if (char.IsDigit(c))
{
numbers += c;
}
}
int result = int.Parse(numbers);
Console.WriteLine("The extracted number is: " + result);
}
```
这个函数会将输入字符串中的数字提取出来,并将其存储在一个名为 `result` 的局部变量中。你可以根据自己的需要修改这个函数,例如将 `int` 类型改为 `double` 类型,或者修改输出语句以适应你的应用场景。
相关问题
用Csharp完成,将一个字符串分为两个子字符串,并输出后一个子字符串
string str = "hello world";
int middle = str.Length / 2; // 计算字符串中间位置
string str1 = str.Substring(0, middle); // 获取前一半子字符串
string str2 = str.Substring(middle); // 获取后一半子字符串
Console.WriteLine(str2); // 输出后一半子字符串
C#,string的中间有一个字母,字母两边是数字。怎么按照字符串的行驶把两边的数字提取出来并存储在两个字符串中
可以使用正则表达式来匹配这个字符串。以下是一个示例代码:
```csharp
string input = "A123B";
Match match = Regex.Match(input, @"(\d+)(\w)(\d+)");
if (match.Success)
{
string num1 = match.Groups[1].Value; // 存储第一个数字
string num2 = match.Groups[3].Value; // 存储第二个数字
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
}
else
{
Console.WriteLine("No match found.");
}
```
正则表达式 `(\d+)(\w)(\d+)` 匹配一个或多个数字,然后一个字母,然后再匹配一个或多个数字。`(\d+)` 和 `(\d+)` 分别用于捕获第一个和第二个数字,而 `\w` 用于匹配字母。`match.Groups[1].Value` 和 `match.Groups[3].Value` 分别用于获取第一个和第二个数字的字符串值。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)