开发者

using java , what are the methods to find a word inside a string?

if i have a string str that is: a>b

what is the best way to find if string str has a > ?do i use:

delimiter =">"

str.split(delimter)

or

str.contains(">")

or regular expression? actually i would prefe开发者_JAVA百科r using regular expression, how to use regular expression in this case?

thanks for the help


It would be

System.out.println("a>b".matches(".*>.*"));

But in this case, I would just go with contains


That one's easy. Actually, you don't need to do the whole Pattern definition mess. You can just call matches.

str.matches(".*>.*");


String.indexOf() returns the index within the string of the first occurence of the specified character or substring

you could also use

String.contains() checks if the string contains a specified sequence of char values


You could use indexOf(int ch) function (found in java.lang.String).It returns position of character in the String or -1 on failure. example:

String s="a>b";
if(s.indexOf('>')!=-1) {
   System.out.println("> is in there");
}

Note: It searches the first occurrence of charcter or substring.


I don't think you should use the regular expression here. But yet if you want to use it you may try this function.

private int getWordCount(String word,String source){
        int count = 0;
        {
            Pattern p = Pattern.compile(word);
            Matcher m = p.matcher(source);
            while(m.find()) count++;
        }
        return count;
    }

You can call if(getWordCount(">","a>b")>0) S.o.p("String contains >");

Thanks,

Mayur Shah (www.MayurShah.in)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜