String s="abcdefg"; int i=s.indexOf("d");//字符d出现的位置
给你个简单的实现public class StringInd { public static void main(String args[]) { String s = "我们是朋友,我们是同学,我们是同事,我的学校,我的房子。"; int len = s.length(); int num = 0; for (int i = 0; i < len; i++) { if (s.charAt(i) == '我') { num++; System.out.println("出现的位置是:" + i); } } System.out.println("出现的次数:" + num); }}
如果真实想搞Java了,那么API是离不开的
charAt,indexOf,split,substring等
出现的次数就是指的是:支配者问题,google就可以了。
String s="abcdefg";
int i=s.indexOf("d");//字符d出现的位置
public static void main(String args[]) {
String s = "我们是朋友,我们是同学,我们是同事,我的学校,我的房子。";
int len = s.length();
int num = 0;
for (int i = 0; i < len; i++) {
if (s.charAt(i) == '我') {
num++;
System.out.println("出现的位置是:" + i);
}
}
System.out.println("出现的次数:" + num);
}}
但是随着解决问题的次数增多会逐渐的熟悉起来
而且会立竿见影,还会有很多意外的收获
String s = "我们是朋友,我们是同学,我们是同事,我的学校,我们的我们房子。";
int num = 0;
String splitString = "我们";
for (int i = 0; i < s.split(splitString).length-1; i++) {
System.out.println("在的位置:" + (s.indexOf(splitString) + num));
num += s.split(splitString)[i+1].length()+splitString.length();
}
System.out.println("出现的次数:" + (s.split(splitString).length - 1));
}
楼上的正解。
/*功能:返回串os中子串word出现的总次数及每一次出现的位置
*@param os 源串
*@param word 子串
*@return int[] --int[0],int[1],..依次放
*每一次出现的位置
* */
public static int[] count(String os,String word)
{
ArrayList<Integer> al=new ArrayList<Integer>();
int pos=-1,cc=0;
while((pos=os.indexOf(word,pos+1))!=-1)
{
cc++;
al.add(pos);
}
int[] r=new int[al.size()];
for(int i=0;i<al.size();i++)
{
r[i]=al.get(i);
}
return r;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="我们是朋友,我们是同学,我们是同事,我的学校,我的房子.";
int[] r=count(s, "我");
System.out.print("总次数:"+r.length+" 每一次位置:");
for(int e:r)
{
System.out.print(e+" ");
}
}
}
程序运行结果:
总次数:5 每一次位置:0 6 12 18 23
多动动手,其实解决问题就是那么简单.
我不是不想查了,是不知道查呵呵,我刚刚才学完String字符串