ccot
ccot

Reputation: 1873

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 prefer using regular expression, how to use regular expression in this case?

thanks for the help

Upvotes: 2

Views: 740

Answers (5)

Help seeker
Help seeker

Reputation: 43

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)

Upvotes: 0

Suhail Gupta
Suhail Gupta

Reputation: 23216

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.

Upvotes: 0

bluefoot
bluefoot

Reputation: 10580

It would be

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

But in this case, I would just go with contains

Upvotes: 3

edgarmtze
edgarmtze

Reputation: 25048

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

Upvotes: 0

squawknull
squawknull

Reputation: 5191

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

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

Upvotes: 0

Related Questions