简体   繁体   中英

How to get the last index of a string value

Below is the code:

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

The CBNotesInqAndMaintRequest contains request data member noteline1---noteline18. once I read the name of one of the data member, I want to get its last index. For eg. If the name of the request object is "noteline8", I want to get the index as 8.

For this I have written the below code:

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

But the above code is returning the index as 0.

It that what you want ?

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

It looks like you want to get the number after 'noteline'. If that is the case:

index = int.Parse(reqPropertyInfo.Name.SubString(8));
index = reqPropertyInfo.Name.Length -1;

在“noteline18”的情况下,你想找到 1 而不是 8 的索引,然后

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

The reason you are getting 0 back is that it is returning the last index of the entire string "noteline", which is of course, always at position 0. If you had "notelinenoteline", it would be returning "8".

Now, as to what you want to get back:

index = reqPropertyInfo.Name.Substring(8);

I created a RegEx solution that doesn't matter what the property name is, but grabs the last digits and returns an integer

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;
}

Usable in your example like so:

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

LastIndexOf返回您要查找的字符串的起始索引,这就是它返回 0 的原因。

Edit

Considering your comment, you should do:

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

我认为最简单的答案是获取字符串的计数,然后将其减去 1,将为您提供该字符串的最后一个索引,如下所示:-

int lastIndex= sampleString.Count-1; //sampleString is the string here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM