反向索引中的子字符串速度快!
我想知道以反向模式在字符串上使用子字符串函数的最佳方法是什么?
例如,我有一个像这样的字符串:
string mainStr= @"CDM\D1_1";
现在我想检查最后两个字符是否等于“_1”。注意:我不想在下划线上使用 split。只是寻找最快的方法来执行反向子字符串,即从字符串中的最后一个字符开始并结束到第一个字符。到目前为止我已经尝试过了,但不确定是否有效!
string revStr = new string(mainStr.ToCharArray().Reverse().ToArray());
if (revStr.Substring(0, 2) == "_1")
{
//Do blah blah
}
更新
很抱歉打扰大家,但今天是星期一,你知道!所以问题是我应该在反转数组后检查“1_”。但最好按照下面的建议使用 string.EndsWith 。
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 problem was I should check for "1_" after reversing the array. Yet it better to do with string.EndsWith as suggested below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用内置的 string.EndsWith 方法,并且string.StartsWith。
Use the built-in string.EndsWith method, and string.StartsWith.
呃。你没有测试过吗?
我会使用 var index = str.LastIndexOf("_1");
你让我很困惑。在这种情况下,您的示例不应该包含
sub.Substring(0, 2) == "1_"
吗?ehh. Haven't you tested it?
I would use
var index = str.LastIndexOf("_1");
You are confusing me. Shouldn't your example contain
sub.Substring(0, 2) == "1_"
in that case?