Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java | compare char word in a char array

Tags:

java

search

char

How do I get the index of a single word (represents in a char array) which can be found in a paragraph (again represents in a char array).

the char represents the word

char word[] = new char[]{'w','o','r','d'};

and here's the paragraph

char para[] = new char[]{'f','g','q','z','y','i','o','p','w','o','r','d'};

I would like to get the index of the first letter in this case 8th. I used binary search by when sorting the words get scrambled.

Thanks.

like image 518
Switch Avatar asked Jan 22 '23 18:01

Switch


1 Answers

A bit inefficient theoretically, but rather practical and simple:

int position = new String(paragraph).indexOf(new String(word));

If you want to understand how this works - check the static int indexOf(..) method of java.lang.String

like image 63
Bozho Avatar answered Jan 28 '23 18:01

Bozho