java indexOf()

来源:百度知道 编辑:UC知道 时间:2024/05/28 16:04:40
题目:String str="@55@55@"
结果:@出现的的位置是036

提问:用控制台语句怎么实现?

public class MyTest{
public static void main(String[] args) {
String chuan="@55@55@";
String cha = "@";
int flag = 0,sum = 0;
String tempStr = chuan;
while(true){
flag = tempStr.indexOf(cha);
if(flag==-1) //没找到
break;
tempStr = "`"+tempStr.substring(flag+1); //重新构造字符串,以便计数
sum += flag;
System.out.println(sum + "\t");
}
}
}

String str = "@55@55@" ;
StringBuilder sbd = new StringBuilder(str);
int i ;
System.out.print("@出现的位置是:");
while((i=sbd.indexOf("@"))>-1){
sbd.replace(i, i+1, "1");//用其他字符替换@
System.out.print(i);//@的位置
}

呵呵,我就爱凑热闹,我给个更好的解决方法
匿名是怕别人笑话我抢分~好方法不能独自享用

//: IndexTest.java
public class IndexTest {
public static void main(String[] args) {
String test = "@55@55@";