0

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 
1
  • unless you have a tab in between each word, use split(" "), as you want to split the String at its white spaces and not at tabbed spaces Commented Jul 22, 2012 at 16:41

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

1

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

Comments

1

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.