[英]Using substring function in C# gives ArgumentOutOfRangeException exception
如何从string pid = {id=2}
提取值2。
我的代码看起来像
string pidnew= pid.Substring(3,5)
它向我显示错误,我做错了什么吗?
要从string pid = "{id=2, genderid=5, stateid=4}"
这样的string pid = "{id=2, genderid=5, stateid=4}"
获取单个值,可以使用以下方法:
public string GetValue(string idPart, string test)
{
var escIdPart = Regex.Escape(idPart);
var pattern = string.Format("(?<=[\\{{\\s,]{0}\\s*=\\s*)\\d+", escIdPart);
var result = default(string);
var match = Regex.Match(test, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
result = match.Value;
}
return result;
}
...
var pid = "{id=2, genderid=5, stateid=4}";
var id = GetValue("id", pid); // returns "2"
var genderid = GetValue("genderid", pid); // returns "5"
var stateid = GetValue("stateid", pid); // returns "4"
如果只有一个数字,您可以对其进行正则表达式
string pidnew = Regex.Match(pid, @"\d+").Value;
而且您无需担心位置
如果要在stateid上进行匹配:
string pidnew = Regex.Match(pid, @"(?<=stateid=)\d+",RegexOptions.IgnoreCase).Value;
Substring
的第二个参数Substring
要采用的字符数。 因此,如果您具有字符串“ {id = 2}”并执行string pidnew= pid.Substring(3,5)
,则您要说的是:“从字符串(第四个字符)的字符索引3开始,并且取五个字符”。 这意味着该字符串至少需要8个字符长。 由于只想使用一个字符,因此将第二个参数更改为1。如果括号是字符串的一部分,则也应从索引4而不是3开始。
您实际需要的是: string pidnew= pid.Substring(4,1);
参量
startIndex类型:System.Int32在此实例中子字符串的从零开始的字符位置。
length类型:System.Int32子字符串中的字符数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.