我想找到一个字符串的最后一个字符位置然后放入一个IF,说明如果最后一个字符位置等于AB或C则执行某个操作.我如何获得最后一个角色位置?
编辑:示例:stringMain ="嗨,这是罗伯特!" subString ="this"现在,我想在stringMain中找到s(s)的位置.
小智 36
使用endswith字符串的方法:
if (string.EndsWith("A") || string.EndsWith("B"))
{
//do stuff here
}
Run Code Online (Sandbox Code Playgroud)
下面是解释此方法的MSDN文章:
http://msdn.microsoft.com/en-us/library/system.string.endswith(v=vs.71).aspx
tle*_*leb 10
有一个从末尾开始索引运算符,如下所示:^n。
var list = new List<int>();
list[^1] // this is the last element
list[^2] // the second-to-last element
list[^n] // etc.
Run Code Online (Sandbox Code Playgroud)
有关索引和范围的官方文档描述了该运算符。需要注意的一件事是:如果列表 ( ) 中没有足够的元素,则该运算符可能会在运行时失败System.ArgumentOutOfRangeException。
我假设你实际上并不想要最后一个字符位置(可能是yourString.Length - 1),而是最后一个字符本身.您可以通过使用最后一个字符位置索引字符串来找到它:
yourString[yourString.Length - 1]
Run Code Online (Sandbox Code Playgroud)
string是一个zero based数组char.
char last_char = mystring[mystring.Length - 1];
Run Code Online (Sandbox Code Playgroud)
至于问题的第二部分,如果char是A,B,C
运用 if statement
char last_char = mystring[mystring.Length - 1];
if (last_char == 'A' || last_char == 'B' || last_char == 'C')
{
//perform action here
}
Run Code Online (Sandbox Code Playgroud)
运用 switch statement
switch (last_char)
{
case 'A':
case 'B':
case 'C':
// perform action here
break
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37112 次 |
| 最近记录: |