C# 如何从C中的字符串中提取负整数和正整数#
当我需要代码显示错误信息时,代码将显示C# 如何从C中的字符串中提取负整数和正整数#,c#,.net,C#,.net,当我需要代码显示错误信息时,代码将显示ten int _userInt = 0; string _checkForNumbers = "Mitchell, -10"; var _intInput = string.Join("", _checkForNumbers.Where(char.IsDigit)); int.TryParse(_intInput, out _userInt); if(_userInt < 0) { Console.WriteLine("Please only e
ten
int _userInt = 0;
string _checkForNumbers = "Mitchell, -10";
var _intInput = string.Join("", _checkForNumbers.Where(char.IsDigit));
int.TryParse(_intInput, out _userInt);
if(_userInt < 0)
{
Console.WriteLine("Please only enter positive numbers");
Console.ReadKey(true);
}
else
{
Console.Write($"{_userInt}");
Console.ReadKey(true);
}
int\u userInt=0;
字符串_checkForNumbers=“Mitchell,-10”;
var _intInput=string.Join(“,_checkForNumbers.Where(char.IsDigit));
int.TryParse(_intInput,out _userInt);
如果(_userInt<0)
{
Console.WriteLine(“请仅输入正数”);
Console.ReadKey(true);
}
其他的
{
Console.Write($“{u userInt}”);
Console.ReadKey(true);
}
我认为这个简单的linq应该可以工作
int temp = 0;
var strInt = checkForNumbers.Split().First(x => int.TryParse(x, out temp));
我认为这个简单的linq应该可以工作
int temp = 0;
var strInt = checkForNumbers.Split().First(x => int.TryParse(x, out temp));
使用System.Text.RegularExpressions
string src = "Mitchell, 4-10-5arbitrary-text3";
var matches = Regex.Matches(src, @"-?\d+");
matches[0].Value; //4
matches[1].Value; //-10;
matches[2].Value; //-5
matches[3].Value; //3
这些值是string
,您需要调用int.Parse
来获取整数值
使用System.Text.RegularExpressions
string src = "Mitchell, 4-10-5arbitrary-text3";
var matches = Regex.Matches(src, @"-?\d+");
matches[0].Value; //4
matches[1].Value; //-10;
matches[2].Value; //-5
matches[3].Value; //3
这些值是string
,您需要调用int.Parse
来获取整数值
尝试用正则表达式提取数字
public static decimal[] intRemover (string input)
{
int n=0;
MatchCollection matches=Regex.Matches(input,@"[+-]?\d+(\.\d+)?");
decimal[] decimalarray = new decimal[matches.Count];
foreach (Match m in matches)
{
decimalarray[n] = decimal.Parse (m.Value);
n++;
}
return decimalarray;
}
尝试用正则表达式提取数字
public static decimal[] intRemover (string input)
{
int n=0;
MatchCollection matches=Regex.Matches(input,@"[+-]?\d+(\.\d+)?");
decimal[] decimalarray = new decimal[matches.Count];
foreach (Match m in matches)
{
decimalarray[n] = decimal.Parse (m.Value);
n++;
}
return decimalarray;
}
公共无效尝试此()
{
字符串模式=@“\-*\d+”;
字符串值=“Mitchell,-10”;
匹配oMatch=Regex.Match(值、模式);
if(int.Parse(oMatch.Value)<0)
{
控制台写入线(oMatch.Value);
Console.ReadKey(true);
}
其他的
{
控制台写入线(oMatch.Value);
Console.ReadKey(true);
}
}
公共无效尝试此()
{
字符串模式=@“\-*\d+”;
字符串值=“Mitchell,-10”;
匹配oMatch=Regex.Match(值、模式);
if(int.Parse(oMatch.Value)<0)
{
控制台写入线(oMatch.Value);
Console.ReadKey(true);
}
其他的
{
控制台写入线(oMatch.Value);
Console.ReadKey(true);
}
}
你应该考虑使用控制台。写(StackOverflow),欢迎你,谢谢你发布你的第一个问题。为了得到最好的答案,问题应该清楚地说明你正在努力实现什么,以及你为达到现在的目标做了什么。有一个,请考虑阅读它和编辑你的问题更清楚你想要什么。你应该考虑使用控制台。写(StackOverflow),欢迎你,谢谢你张贴你的第一个问题。为了得到最好的答案,问题应该清楚地说明你正在努力实现什么,以及你为达到现在的目标做了什么。有一个,请考虑阅读它和编辑你的问题更清楚你想什么。这将选择- 1作为一个数字,这将选择- 1作为一个数字。