Skip to main content
 首页 » 编程设计

C# String elemenths 范围 ":"等效

2024年02月13日11xiaohuochai

是否可以像在 Python 中那样使用“:”快速显示 String elemenths 范围,谢谢!

例如

Python 
s="abazvbn" 
print(s[2:5]) //It will display string elemenths from 2 to 5 ('azvb') 

C# 是否可以在不使用循环的情况下在 C# 中执行此操作。目前可以这样做

String s="abazvbn" 
for(int i=2;i<5;i++) 
COnsole.WriteLine(s[i]) 

请您参考如下方法:

同样,您有 String.Substring()方法。参数略有不同。您传入起始索引和要返回的子字符串的长度。

或者您可以创建一个Slice() 扩展方法。将其放在静态类中。

public static class StringExtensions 
{ 
    public static string Slice(this string s, int startIndex, int endIndex) 
    { 
    int length = endIndex - startIndex + 1;               // Calculate length 
    return s.Substring(startIndex, length); // Return Substring of length 
    } 
} 

然后你可以像这样使用它......

string mystring = "abazvbn"; 
string myslice = mystring.Splice(2, 5);//myslice is azvb