简体   繁体   English

C# 从字符串中获取最后n个字符的8种方法

[英]C# 8 way to get last n characters from a string

Recently VS hinted me to use the:最近 VS 提示我使用:

var str = "foo";
var str2 = str[^2..];

Instead of the:而不是:

var str = "foo";
var str2 = str.Substring(str.Length - 2);

So, my question is are there any differences between the str[^2..] and the str.Substring(str.Length - 2) ?所以,我的问题是str[^2..]str.Substring(str.Length - 2)之间有什么区别吗? I think it is a new C# feature, but I was not able to find any documentation about it.我认为这是一个新的 C# 功能,但我找不到任何有关它的文档。 So, I do not know how it is called and what version of C# does it come with.所以,我不知道它是怎么叫的,它是什么版本的C#。

Here is what I was trying to google:这是我试图用谷歌搜索的内容:

^ in string access c#

I did not get any related results.我没有得到任何相关的结果。 Should I google something else?我应该谷歌其他东西吗?

Commenters did a great job on this, but I'm gonna put an answer here so the question can be considered answered.评论者在这方面做得很好,但我会在这里给出一个答案,这样这个问题就可以被认为是回答了。

There is no difference.没有区别。 It's just syntax sugar.这只是语法糖。 Here's what LINQPad shows you'd get in "C# 1.0" terms:以下是 LINQPad 显示的“C# 1.0”术语:

   string str = "foo";
   int length = str.Length;
   int num = length - 2;
   int length2 = length - num;
   string str2 = str.Substring (num, length2);

Others are correct in that it is just syntax sugar but there is some slight differences.其他人是正确的,因为它只是语法糖,但有一些细微的差别。 They both call "Substring" however the hat version calls the String.Substring(Int32, Int32) signature and the later conventional version calls String.Substring(Int32) signature.它们都称为“子字符串”,但帽子版本调用 String.Substring(Int32, Int32) 签名,而后来的常规版本调用 String.Substring(Int32) 签名。

It's interesting that even though str[^2..] produces more code it seems to have slightly better performance in my quick benchmark.有趣的是,尽管 str[^2..] 生成了更多代码,但在我的快速基准测试中它的性能似乎稍好一些。

var str = "foo";
var str2 = str[^2..];
========generates the following IL=============
   nop  
   ldstr    "foo"
   stloc.0     // str
   ldloc.0     // str
   dup  
   callvirt String.get_Length ()
   dup  
   ldc.i4.2 
   sub  
   stloc.2  
   ldloc.2  
   sub  
   stloc.3  
   ldloc.2  
   ldloc.3  
   callvirt String.Substring (Int32, Int32)
   stloc.1     // str2
   ldloc.1     // str2
   call Console.WriteLine (String)
   nop  
   ret

And the following conventional version.以及以下常规版本。

var str = "foo";
var str2 = str.Substring(str.Length - 2);
========generates the following IL=============
   nop  
   ldstr    "foo"
   stloc.0     // str
   ldloc.0     // str
   ldloc.0     // str
   callvirt String.get_Length ()
   ldc.i4.2 
   sub  
   callvirt String.Substring (Int32)
   stloc.1     // str2
   ldloc.1     // str2
   call Console.WriteLine (String)
   nop  
   ret  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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