2012-07-26 226 views
1

我知道它是一个愚蠢的问题,但我真的被困在它。以下是代码:如何获取字符串值的最后一个索引

PropertyInfo[] requestPropertyInfo; 
requestPropertyInfo = typeof(CBNotesInqAndMaintRequest).GetProperties(); 

CBNotesInqAndMaintRequest包含请求数据成员noteline1 --- noteline18。一旦我读取数据成员之一的名称,我想要得到它的最后一个索引。例如。如果请求对象的名称是“noteline8”,我想要得到的指数为8

为此,我写了下面的代码:

foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo) 
{ 
    index = reqPropertyInfo.Name.LastIndexOf("noteline"); 
} 

但上面的代码返回指数0.1请帮助

+0

@Kenda llFrey看看他的问题。提供的答案往往非常好,而且OP本人已经承认他们的正确性 - 只是不接受他们。需要30秒才能回过头来接受答案。有时只需要提示。 – 2012-07-26 18:28:33

回答

1

我创建了一个正则表达式的解决方案,不要紧属性名称是什么,但抓住最后的数字,并返回一个整数

static int GetLastInteger(string name) { 

    int value; 
    if(int.TryParse(name, out value)) { 
     return value; 
    } 
    System.Text.RegularExpressions.Regex r = 
     new System.Text.RegularExpressions.Regex(@"[^0-9](\d+\b)"); 

    System.Text.RegularExpressions.Match m = 
     r.Match(name); 

    string strValue = m.Groups[1].Value; 
    value = (int.Parse(strValue)); 
    return value; 
} 

可用在你的榜样,像这样:

foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo) 
{ 
    index = GetLastInteger(reqPropertyInfo.Name); 
} 
+1

我可以建议'\ d + $'代替。 – 2012-07-26 16:02:58

0

LastIndexOf返回你要找的字符串,这就是为什么它返回0

+0

这将提供值-1 + 8。即7.我想得到值8(如果名字是noteline8)。如果名称是noteline1,那么它应该为我提供1 – 2012-07-26 15:32:03

1

您得到0回来的原因的起始索引的是,它返回的最后一个索引整个字符串“n oteline“,当然总是在位置0.如果你有”notelinenoteline“,它会返回”8“。

现在,为你回去:

index = reqPropertyInfo.Name.Substring(8); 
3

这是你想要的吗?

foreach (PropertyInfo reqPropertyInfo in requestPropertyInfo) 
{ 
    index = int.Parse(reqPropertyInfo.Name.Replace("noteline","")); 
} 
2

它看起来像你想得到'noteline'后的数字。如果是这样的话:

index = int.Parse(reqPropertyInfo.Name.SubString(8)); 
+0

我想要得到名称noteline1,noteline2,noteline3,--- noteline18(即1,2,3,4,5-18)的整数部分。我将如何实现它 – 2012-07-26 15:42:04

+0

@HimanshuNegi:这个答案告诉你如何。如果'reqPropertyInfo.Name'是'“noteline123”',那么索引将变为'123'。 – 2012-07-26 16:04:28

0

编辑

考虑您的意见,你应该做的:

Int32 index = Convert.ToInt32(reqPropertyInfo.Name.Replace("noteline","")); 
+0

我想要得到名称noteline1,noteline2,noteline3,--- noteline18(即1,2,3,4,5-18)的整数部分。我将如何实现它 – 2012-07-26 15:40:31

+0

@HimanshuNegi现在就看到我的编辑。 – 2012-07-26 16:43:15

1
index = reqPropertyInfo.Name.Length -1; 

柜面 “noteline18” 的,你想找到索引1代替8,那么

index = reqPropertyInfo.Name.LastIndexOf('e') + 1 
0

的在我看来最简单的答案是获得字符串的计数,然后减1,将给你该字符串的最后一个索引,如下所示: -

int lastIndex= sampleString.Count-1; //sampleString is the string here. 
相关问题