在各种文本处理任务中,我们经常需要在给定的字符串中找到特定字符的第n个最后一次出现。此外,这一操作在解析日志、分析文本数据或从字符串中提取相关信息等任务中特别有用。
在本教程中,我们将探索使用Java在字符串中查找字符的第n个最后一次出现的多种技术。
2. 使用传统循环
找到字符串中字符的第n个最后一次出现的一个传统方法是通过迭代循环。在这种方法中,我们从字符串的末尾开始迭代,直到达到所需位置,计算目标字符的出现次数。
让我们看看这如何实现:
String str = "Welcome to Baeldung";
char target = 'e';
int n = 2;
int expectedIndex = 6;
@Test
public void givenStringAndCharAndN_whenFindingNthLastOccurrence_thenCorrectIndexReturned() {
int count = 0;
int index = -1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == target) {
count++;
if (count == n) {
index = i;
break;
}
}
}
assertEquals(expectedIndex, index);
}
大约 3 分钟