Jack Morton
Jack Morton

Reputation: 199

compare strings method

I would like to compare strings but the following code won't work. I'm guessing it's because incompatible, is there any other way to do it?Thanks!

 public class test
 {
    public static void main(String[] args)
    {
       String str1 = "abc def ghi abc ded abc ghi";
       String str2 = "ghi";
       int count = 0;

         String array[] = str1.split("\t");
         for(int i = 0; i < array.length; i++)
         {
           if(array[i].equals(str2))
           {
             count++;
             System.out.println(array[i]);  
             System.out.println(count);     
           } 

       }//for

      }//main

     }//test

Upvotes: 0

Views: 150

Answers (4)

gg13
gg13

Reputation: 574

If you don't want to use split, you can use the StringTokenizer class also. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html I find this most useful. You can create a StringTokenizer for each string like this.

StringTokenizer st1 = new StringTokenizer(str1," ");

The " " after the str1 indicates which things to parse by. So if you wanted to parse by a comma, dash, number, letter, anything, just put it there!

Then create an array based on the number of tokens it finds like this:

String[] array1 = new String[st1.countTokens()];

Fill the array like this:

for(int i=0;i<st1.countTokens();i++)
{  
    array1[i]=st1.nextToken(); 
}

You could similarly do this with str2, and compare this way! This is just a different way to do this as you asked. Otherwise, changing the "/t" to " " will work with the split as said in other answers.

Hope this helps!

Upvotes: 1

Bytecode
Bytecode

Reputation: 6591

String has contains method it help to find out the occurance of an item . in your case str1.contains(str2)

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Do NOT use "\t" but use " " instead, and it works.....

"\t" will be useful only if you are have "tab" used instead of space.

Try this now..

public class T
{
   public static void main(String[] args)
   {
      String str1 = "abc def ghi abc ded abc ghi";
      String str2 = "ghi";
      int count = 0;

        String array[] = str1.split(" ");
        for(int i = 0; i < array.length; i++)
        {
          if(array[i].equals(str2))
          {
            count++;
            System.out.println(array[i]);  
            System.out.println(count);     
          } 

      }//for

     }//main

    }//test

Upvotes: 1

sblom
sblom

Reputation: 27343

It looks like you're splitting on "\t" (tab), but your string is " " (space) separated. Try String array[] = str1.split(" "); instead.

Upvotes: 4

Related Questions