我想找到一个字符串的最后一个字符位置,然后放入一个IF,说明如果最后一个字符的位置等于A B或C,那么做一个特定的动作。我如何获得最后的角色位置?如何使用C#获取字符串中子字符串的最后一个字符位置?
编辑: 例如: stringMain =“嗨,这是罗伯特!” subString =“this” 现在,我想要在stringMain中找到s(s的位置)。
我想找到一个字符串的最后一个字符位置,然后放入一个IF,说明如果最后一个字符的位置等于A B或C,那么做一个特定的动作。我如何获得最后的角色位置?如何使用C#获取字符串中子字符串的最后一个字符位置?
编辑: 例如: stringMain =“嗨,这是罗伯特!” subString =“this” 现在,我想要在stringMain中找到s(s的位置)。
使用字符串方法:
if (string.EndsWith("A") || string.EndsWith("B"))
{
//do stuff here
}
继承人的MSDN文章解释这个方法:
http://msdn.microsoft.com/en-us/library/system.string.endswith(v=vs.71).aspx
我以为你不真正想要的最后一个字符位置(这将是yourString.Length - 1
),但最后一个字符本身。你可以发现,通过与最后一个字符位置索引字符串:
yourString[yourString.Length - 1]
string
是zero based
阵列的char
。
char last_char = mystring[mystring.Length - 1];
至于问题的第二部分,如果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
}
使用switch statement
switch (last_char)
{
case 'A':
case 'B':
case 'C':
// perform action here
break
}
'if'看起来会更好,因为'switch',imo。 – oscilatingcretin 2013-02-10 03:20:58
我只是写作开关,但有问题需要if语句! – 2013-02-10 03:21:52
我喜欢使用LINQ:
YourString.Last()
你需要导入System.Linq命名空间,如果你还没有它。尽管如此,我不会导入命名空间来使用.Last()。
可能不是最快的,但绝对有趣。 – John 2013-02-10 03:23:10
最后的字符位置......是不是只是'长度1'? – spender 2013-02-10 03:04:05
请阅读有关'String'类的文档,地址为:http://msdn.microsoft.com/en-us/library/system.string.aspx – 2013-02-10 03:04:32
如果您从VB来到C#,您可能会发现“C#&VB.NET转换“很有帮助。 http://www.amazon.com/gp/product/0596003196/ref=oh_details_o02_s00_i00 – John 2013-02-10 03:25:54