Topic: 查找字符串的位置

  Print this page

1.查找字符串的位置 Copy to clipboard
Posted by: sunandjava
Posted on: 2006-09-23 09:06


import java.io.*;
public class Search1
{
public static void main(String args[])
{
int count=0,first=0,second=0;
String text="ab cd ef g";
String s="";
String subtext=text;
System.out.println(text);
System.out.println("请输入你要查找的字符串:");
try
{
BufferedReader in=new BufferedReader(new InputStreamReader (System.in));
s=in.readLine();
}
catch(IOException e){}
for(int i=1;i<=text.length();i+=second+1)
{
second=subtext.indexOf("");
String temp=subtext.substring(first,second);
if(s.equalsIgnoreCase(temp)) count++;
subtext=subtext.substring(second+1);
}


if(count==0)
System.out.print("it not exists");
else
System.out.print("it exists");
}
}

请大伙帮我看看这个程序啊,我搞了好久 了都没有结果,现在只有寄希望于各位大虾了(要求:输入任意的字符串,能够查找到它是否存在,最好还能统计一下这个字符串总共出现了几次,以及它出现的位置.)

2.Re:查找字符串的位置 [Re: sunandjava] Copy to clipboard
Posted by: wwhui
Posted on: 2006-09-24 12:46

catch(IOException e){};
你掉了个分号,再试一下!!

3.Re:查找字符串的位置 [Re: sunandjava] Copy to clipboard
Posted by: why
Posted on: 2006-09-24 18:53

    
// for (int i = 1; i <= text.length(); i += second + 1) {
// second = subtext.indexOf("");
// String temp = subtext.substring(first, second);
// if (s.equalsIgnoreCase(temp))
// count++;
// subtext = subtext.substring(second + 1);
// }

boolean isEnd = false;
first = 0; // start pos to search from, check API doc of String.indexOf
count = 0;
while (! isEnd){
int pos = text.indexOf(s, first);
if (pos > 0) {
count ++;
first = pos + 1;
System.out.println(pos);
} else {
isEnd = true;
}
}

    if (count == 0)
      System.out.print("it does not exist");


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923