如何在字符串中找到最后一个字母,并获取其索引?

时间:2016-04-09 09:18:13

标签: c# string visual-studio-2015

假设我有一个名为test的字符串,

string test = "hello my dear world"

我希望获得最后一个字母的索引(即19)。

如何获取该索引,并将其插入到int / string中?

4 个答案:

答案 0 :(得分:4)

非常简单。

string test = "Hello World";
char theLastCharacterOfTest = test[test.Length - 1]; // 'd'
int theIndexOfTheLastCharacter = test.Length - 1; // 10

想要解释一下?在这里!

让我们从获取最后一个字符的索引开始。由于C#使用基于0的索引系统(即第一个索引为0),因此最后一个索引是字符串的长度-1。

最后一个字符只是最后一个索引的字符,对吗?并且string的索引器返回传入的索引处的字符。如果我们将这两者结合起来,我们得到test[test.Length - 1]

我不认为你对索引器很熟悉,所以这里有一个链接:

https://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

答案 1 :(得分:2)

我不确定您是否正在寻找最后一个字符的索引位置(您说索引是19,但是& #39; s位置......索引是18)。以下是:

string test = "hello my dear world";

// The length of the text gives the position of the last char
int position = test.Length;

// C# has a 0-based index. You need the string length -1 to get the last char's position
int index = test.Length - 1;

此处a working example

答案 2 :(得分:0)

int index = test.Length;
char LastLetter = test[index - 1];

请在发布问题之前进行搜索。

答案 3 :(得分:0)

string test = "hello my dear world";

int index = test.FindIndex(x => x.StartsWith("d"));

int index = test.Length - 1;