思路:可以将字符串句子按照空格分割,然后存入数组,定义一个变量。遍历数组,寻找想要的字符串,如果找到,就将该字符串的索引赋值给变量,
如果后面依旧存在你想要的字符串,那么此前的变量就会被最新的索引值覆盖掉,最后输出这个变量对应数组中的字符串即可。
String str = "Nature has given us that two ears, two eyes, and but one tongue, to the end that we should hear "
+ "and see more than we speak";
int m = 0;
String[] strNew = str.split(" ");
for(int j = 0; j < strNew.length; j++) {
if(strNew[j].equals("two")) {
m = j;
System.out.println(strNew[m] + m);
}
}
System.out.println( "最后的" + strNew[m] + "在" + m + "," + "转换后为" + strNew[m].substring(0,1).toUpperCase() +
strNew[m].substring(1,strNew[m].length()));
结果: