开发者

SubString in reversed index fast!

开发者 https://www.devze.com 2023-02-25 08:22 出处:网络
I wonder what is the best way to use substring function on a string in reverse mode? For example I have a string like:

I wonder what is the best way to use substring function on a string in reverse mode?

For example I have a string like:

string mainStr= @"CDM\D1_1";

Now I want to check if the last two characed are equal to "_1" or not. Note: I dont want to use split on underscore. Just looking for the fastest way to do a reversed substring that is start from last char in string and end to first char. I tried this so far, but not sure if it works!

string revStr = new string(mainStr.ToCharArray().Reverse().ToArray());
if (revStr.Substring(0, 2) == "_1")
{
   //Do blah blah
}

UPDATE

Sorry to bother guys but it is Monday you know! so the pro开发者_Go百科blem was I should check for "1_" after reversing the array. Yet it better to do with string.EndsWith as suggested below.


Use the built-in string.EndsWith method, and string.StartsWith.


tried this so far, but not sure if it works!

ehh. Haven't you tested it?

I would use var index = str.LastIndexOf("_1");

Just looking for the fastest way to do a reversed substring that is start from last char in string and end to first char. I tried this so far, but not sure if it works!

You are confusing me. Shouldn't your example contain sub.Substring(0, 2) == "1_" in that case?

0

精彩评论

暂无评论...
验证码 换一张
取 消