java中如何高效获得字符串中特定字符的所有位置,比如字符串:12&32&位置&yutye,中的&的所有出现位置?

如题所述

你试下下面的代码能满意吗 ,我已经试过了,可以的:
public static void main(String args[]) {
String str = "12&32&位置&yutye";
System.out.println("&在字符串中出现的位置分别为:");
for(int i=-1; i<=str.lastIndexOf("&");++i)
{
i=str.indexOf("&",i);
System.out.print(i+"\t");

}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-07-26
String str = "12&32&";
int length = str.length();
int[] a = new int[length];
for(int i=0; i<a.length; i++)
{
a[i] = str.indexOf("&");
}
System.out.println("出现的位置为:");
for(int i=0; i<a.length; i++)
{
System.out.print(a[i] + " ");
}
第2个回答  2011-07-25
"12&32&".indexOf('&')