2014-05-14 74 views
0

例如,如果我有用户输入一个字符串,但长度未知,我想从右到左取第三个元素,我该怎么做?在Python它像串[-2]但是,这不是工作在C#..如何从右向左选择元素?

例如:

string whatever = "snfdsjzfs"; 

我想选择z和使用string[6]是不会帮我,因为字符串的长度可能会改变..?

+0

欢迎。常识是[不在标题中包含标签](http://meta.stackexchange.com/questions/103563/can-we-prevent-titles-with-an-unnecessary-tag-in-them) –

回答

1

结合使用String.Chars索引和String.Length属性:在计算器上

int num = ...; // num-th (zero based) char to extract from the end to start 
if (num > whatever.Length-1){ 
    // error handling here 
}  
char res = whatever[whatever.Length-num-1]; 
+0

它是'无论[whatever.Length-NUM-1]'。你有一个错误。零索引集合,单索引长度以及所有这些。 – Servy

+0

@Servy请注意,它是从末尾开始的num-th char,就像第一个将会是'whatever [hatever.Length-1]'一样。 – herohuyongtao

+0

OP的例子使用右手边的零索引索引,这当然是大多数程序员期望的,因为他们是程序员,因此索引是零索引。 – Servy

相关问题