关于在字符串中查找某一个字符的位置的方法

一:准备

在程序的开始,我们可以确定使用一些知识点:

  indexof,lastIndexOf,StringBuilder。

二:程序

  

  public class IndexOfDemo {

    @Test
public void test1(){
String str="agyyayyaooea";
int posi,x=0;
int lastPosi=str.lastIndexOf("a");
StringBuilder sb=new StringBuilder();
for (int i=0;i<str.length();i++){
posi=str.indexOf("a",x);
if (posi!=lastPosi){
sb=sb.append(posi);

}else{
break;
}
x=posi+1;
}
System.out.println(sb.toString());
}
}

三:结果展示

  

四:程序的构建技巧

  1.使用容器来存储位置,比数组固定个数来确定位置节省空间使用

  2.for循环结束的条件同样可以减小开销,在程序for之前,可以通过lastIndexOf来确定最后一个字符出现的位置,当for循环时,到这里就可以停止。

  3.而停止更可以使用posi来判断,而不是for里面的i来停止

 
原文地址:https://www.cnblogs.com/juncaoit/p/5923215.html