Given two List sentence and List queries
I have two find the occurrence of queries in sentences.
Example,
"Pulkit likes StackOverflow and coding"
"Pulkit does not like Reddit"
"Pulkit like ice cream"
Queries
Pulkit coding
like
does
The function should return for the queries
sentence[0]
sentence[1], sentence[2]
sentence[1]
I solved this question already using HashMap but it is quadratic and I am wondering how to do it in linear time.
Solution
public static void findMatch(List<String> sentences, List<String> queries) {
// Write your code here
// Split the sentences into terms and map them by index
Map<Integer, Set<String>> sentencesSplit = new HashMap<>();
for (int j = 0; j < sentences.size(); j++) {
String[] splitSentence = sentences.get(j).split(" ");
Set<String> sentenceSet = new HashSet<>();
sentencesSplit.put(j, sentenceSet);
for (int i = 0; i < splitSentence.length; i++) {
sentenceSet.add(splitSentence[i]);
}
}
// Split the query into terms and map them by index
Map<Integer, String[]> queriesSplit = new HashMap<>();
for (int i = 0; i < queries.size(); i++) {
queriesSplit.put(i, queries.get(i).split(" "));
}
for (int i = 0; i < queries.size(); i++) {
String found = null;
for (int j = 0; j < sentences.size(); j++) {
String[] splitQuery = queriesSplit.get(i);
Set<String> sentenceStringList = sentencesSplit.get(j);
boolean notFound = false;
for (int k = 0; k < splitQuery.length; k++) {
if (!sentenceStringList.contains(splitQuery[k])) {
notFound = true;
break;
}
}
if (!notFound) {
if (found == null) {
found = "" + j;
} else {
found += " " + j;
}
}
}
if (found == null) {
found = "-1";
}
System.out.println(found);
}
}
My code is similar with human's thinking.
\b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b.
Hope my code will help you.
public class MainClass {
public static void main(String [] args)
{
List<String> sentences = new ArrayList<String>();
sentences.add("Pulkit likes StackOverflow and coding");
sentences.add("Pulkit does not like Reddit");
sentences.add("Pulkit like ice cream");
List<String> queries = new ArrayList<String>();
queries.add("Pulkit coding");
queries.add("like");
queries.add("does");
findMatch(sentences, queries);
}
public static void findMatch(List<String> sentences, List<String> queries) {
for(String query : queries) {
System.out.print("]");
String match = ".*\\b" + query.replace(" ", "\\b.*") + "\\b.*";
for (int iSentence = 0; iSentence < sentences.size(); iSentence++) {
if(sentences.get(iSentence).matches(match)) {
System.out.print(" " + iSentence);
}
}
System.out.println("");
}
}
}
Console output:
] 0
] 1 2
] 1
Related
import java.util.StringTokenizer;
class Count {
int count;
String name;
void SetCount(int c, String n) {
this.count = c;
this.name = n;
}
void Show() {
System.out.print("Word= " + name);
System.out.print(" Count= " + count);
System.out.println();
}
}
class Contains2 extends Count {
public static void main(String args[]) {
String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out";
int i, c2, j;
StringTokenizer st = new StringTokenizer(s, " ");
c2 = st.countTokens();
String[] test = new String[c2];
Count[] c = new Count[c2];
for (i = 0; i < c2; i++) {
c[i] = new Count();
}
i = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
test[i] = token;
c[i].SetCount(0, test[i]);
i++;
}
for (i = 0; i < c2; i++) {
for (j = 0; j < c2; j++) {
if (c[i].name.equals(test[j]))
c[i].count += 1;
}
}
for (i = 0; i < c2; i++) {
c[i].Show();
}
}
}
so i made this small program to count the number every word was repeated in a paragraph. its working as planned but now i am getting duplicates of every word since i made separate objects for each and printing them all. so is there any way i could delete the duplicate words i mean deleting those objects based on their names. i can set them to null but it would still print them so i just wanna get rid of them or skip them somehow
You cannot adjust the size of a array once it's created. You could only create a new array with a different size and copy the non-null elements.
You could also set elements to null and just ignore those elements for printing...
for (i = 0; i < c2; i++) {
if (c[i] != null)
c[i].Show();
}
An alternative would be using a List, which allows you to remove elements.
Alternatively a Map<String, Integer> mapping from a word to the count could be used. In this case you don't even need the Count class:
String s = "Hello this program will repeat itself for this useless purpose and will not end until it repeats itself again and again and again so watch out";
StringTokenizer st = new StringTokenizer(s, " ");
Map<String, Integer> map = new HashMap<>();
while (st.hasMoreTokens()) {
map.merge(st.nextToken(), 1, Integer::sum);
}
for (Map.Entry<String, Integer> e : map.entrySet()) {
System.out.print("Word= " + e.getKey());
System.out.print(" Count= " + e.getValue());
System.out.println();
}
I have an array of string say
A=["hello", "you"]
I have a string, say
s="hello, hello you are so wonderful"
I need to count the number of occurrence of strings from A in s.
In this case, the number of occurrences is 3 (2 "hello", 1 "you").
How to do this effectively? (A might contains lots of words, and s might be long in practice)
Try:
Map<String, Integer> wordCount = new HashMap<>();
for(String a : dictionnary) {
wordCount.put(a, 0);
}
for(String s : text.split("\\s+")) {
Integer count = wordCount.get(s);
if(count != null) {
wordCount.put(s, count + 1);
}
}
public void countMatches() {
String[] A = {"hello", "you"};
String s = "hello, hello you are so wonderful";
String patternString = "(" + StringUtils.join(A, "|") + ")";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
Note that StringUtils is from apache commons. If you don't want to include and additional jar you can just construct that string using a for loop.
HashSet<String> searchWords = new HashSet<String>();
for(String a : dictionary) {
searchWords.add(a);
}
int count = 0;
for(String s : input.split("[ ,]")) {
if(searchWords.contains(s)) {
count++;
}
}
int count =0;
for(int i=0;i<A.length;i++)
{
count = count + s.split(A[i],-1).length - 1;
}
Working Ideone : http://ideone.com/Z9K3JX
This is fully working method with output :)
public static void main(String[] args) {
String[] A={"hello", "you"};
String s= "hello, hello you are so wonderful";
int[] count = new int[A.length];
for (int i = 0; i < A.length; i++) {
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
}
for (int i = 0; i < count.length; i++) {
System.out.println(A[i] + ": " + count[i]);
}
}
What does this line do?
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
This part s.replaceAll(A[i], "") changes all "hello" to empty "" string in the text.
So I take the length of everything s.length() I substract from it the length of same string without that word s.replaceAll(A[i], "").length() and I divide it by the length of that word /A[i].length()
Sample output for this example :
hello: 2
you: 1
You can use the String Tokenizer
Do something like this:
A = ["hello", "you"];
s = "hello, hello you are so wonderful";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreElements()) {
for (String i: A) {
if(st.nextToken() == i){
//You can keep going from here
}
}
}
This is what I came up with:
It doesn't create any new objects. It uses String.indexOf(String, int), keeps track of the current index, and increments the occurance-count.
public class SearchWordCount {
public static final void main(String[] ignored) {
String[] searchWords = {"hello", "you"};
String input = "hello, hello you are so wonderful";
for(int i = 0; i < searchWords.length; i++) {
String searchWord = searchWords[i];
System.out.print(searchWord + ": ");
int foundCount = 0;
int currIdx = 0;
while(currIdx != -1) {
currIdx = input.indexOf(searchWord, currIdx);
if(currIdx != -1) {
foundCount++;
currIdx += searchWord.length();
} else {
currIdx = -1;
}
}
System.out.println(foundCount);
}
}
}
Output:
hello: 2
you: 1
String database[] = {'a', 'b', 'c'};
I would like to generate the following strings sequence, based on given database.
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
...
I can only think of a pretty "dummy" solution.
public class JavaApplication21 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
String query = "a";
StringBuilder query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
query = query_sb.toString();
System.out.println(query);
}
query = "aa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
query = query_sb.toString();
System.out.println(query);
}
}
query = "aaa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
for (int c = 0; c < database.length; c++) {
query_sb.setCharAt(2, database[c]);
query = query_sb.toString();
System.out.println(query);
}
}
}
}
}
The solution is pretty dumb. It is not scale-able in the sense that
What if I increase the size of database?
What if my final targeted print String length need to be N?
Is there any smart code, which can generate scale-able permutation and combination string in a really smart way?
You should check this answer: Getting every possible permutation of a string or combination including repeated characters in Java
To get this code:
public static String[] getAllLists(String[] elements, int lengthOfList)
{
//lists of length 1 are just the original elements
if(lengthOfList == 1) return elements;
else {
//initialize our returned list with the number of elements calculated above
String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
//the recursion--get all lists of length 3, length 2, all the way up to 1
String[] allSublists = getAllLists(elements, lengthOfList - 1);
//append the sublists to each element
int arrayIndex = 0;
for(int i = 0; i < elements.length; i++){
for(int j = 0; j < allSublists.length; j++){
//add the newly appended combination to the list
allLists[arrayIndex] = elements[i] + allSublists[j];
arrayIndex++;
}
}
return allLists;
}
}
public static void main(String[] args){
String[] database = {"a","b","c"};
for(int i=1; i<=database.length; i++){
String[] result = getAllLists(database, i);
for(int j=0; j<result.length; j++){
System.out.println(result[j]);
}
}
}
Although further improvement in memory could be made, since this solution generates all solution to memory first (the array), before we can print it. But the idea is the same, which is to use recursive algorithm.
This smells like counting in binary:
001
010
011
100
101
...
My first instinct would be to use a binary counter as a "bitmap" of characters to generate those the possible values. However, there are several wonderful answer to related questions here that suggest using recursion. See
How do I make this combinations/permutations method recursive?
Find out all combinations and permutations - Java
java string permutations and combinations lookup
http://www.programmerinterview.com/index.php/recursion/permutations-of-a-string/
Java implementation of your permutation generator:-
public class Permutations {
public static void permGen(char[] s,int i,int k,char[] buff) {
if(i<k) {
for(int j=0;j<s.length;j++) {
buff[i] = s[j];
permGen(s,i+1,k,buff);
}
}
else {
System.out.println(String.valueOf(buff));
}
}
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
char[] buff = new char[database.length];
int k = database.length;
for(int i=1;i<=k;i++) {
permGen(database,0,i,buff);
}
}
}
Ok, so the best solution to permutations is recursion. Say you had n different letters in the string. That would produce n sub problems, one for each set of permutations starting with each unique letter. Create a method permutationsWithPrefix(String thePrefix, String theString) which will solve these individual problems. Create another method listPermutations(String theString) a implementation would be something like
void permutationsWithPrefix(String thePrefix, String theString) {
if ( !theString.length ) println(thePrefix + theString);
for(int i = 0; i < theString.length; i ++ ) {
char c = theString.charAt(i);
String workingOn = theString.subString(0, i) + theString.subString(i+1);
permutationsWithPrefix(prefix + c, workingOn);
}
}
void listPermutations(String theString) {
permutationsWithPrefix("", theString);
}
i came across this question as one of the interview question. Following is the solution that i have implemented for this problem using recursion.
public class PasswordCracker {
private List<String> doComputations(String inputString) {
List<String> totalList = new ArrayList<String>();
for (int i = 1; i <= inputString.length(); i++) {
totalList.addAll(getCombinationsPerLength(inputString, i));
}
return totalList;
}
private ArrayList<String> getCombinationsPerLength(
String inputString, int i) {
ArrayList<String> combinations = new ArrayList<String>();
if (i == 1) {
char [] charArray = inputString.toCharArray();
for (int j = 0; j < charArray.length; j++) {
combinations.add(((Character)charArray[j]).toString());
}
return combinations;
}
for (int j = 0; j < inputString.length(); j++) {
ArrayList<String> combs = getCombinationsPerLength(inputString, i-1);
for (String string : combs) {
combinations.add(inputString.charAt(j) + string);
}
}
return combinations;
}
public static void main(String args[]) {
String testString = "abc";
PasswordCracker crackerTest = new PasswordCracker();
System.out.println(crackerTest.doComputations(testString));
}
}
For anyone looking for non-recursive options, here is a sample for numeric permutations (can easily be adapted to char. numberOfAgents is the number of columns and the set of numbers is 0 to numberOfActions:
int numberOfAgents=5;
int numberOfActions = 8;
byte[][]combinations = new byte[(int)Math.pow(numberOfActions,numberOfAgents)][numberOfAgents];
// do each column separately
for (byte j = 0; j < numberOfAgents; j++) {
// for this column, repeat each option in the set 'reps' times
int reps = (int) Math.pow(numberOfActions, j);
// for each column, repeat the whole set of options until we reach the end
int counter=0;
while(counter<combinations.length) {
// for each option
for (byte i = 0; i < numberOfActions; i++) {
// save each option 'reps' times
for (int k = 0; k < reps; k++)
combinations[counter + i * reps + k][j] = i;
}
// increase counter by 'reps' times amount of actions
counter+=reps*numberOfActions;
}
}
// print
for(byte[] setOfActions : combinations) {
for (byte b : setOfActions)
System.out.print(b);
System.out.println();
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
import java.util.*;
public class Permutation {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("ENTER A STRING");
Set<String> se=find(in.nextLine());
System.out.println((se));
}
public static Set<String> find(String s)
{
Set<String> ss=new HashSet<String>();
if(s==null)
{
return null;
}
if(s.length()==0)
{
ss.add("");
}
else
{
char c=s.charAt(0);
String st=s.substring(1);
Set<String> qq=find(st);
for(String str:qq)
{
for(int i=0;i<=str.length();i++)
{
ss.add(comb(str,c,i));
}
}
}
return ss;
}
public static String comb(String s,char c,int i)
{
String start=s.substring(0,i);
String end=s.substring(i);
return start+c+end;
}
}
// IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}
So this is the continuation of my question from this thread: here
String[] words = {"cowboy", "animal", "monster"};
String[] meanings = {"meaning1", "meaning2", "meaning3"};
boolean check = false;
for (int i = 0; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
} else {
}
}
if (check) {
System.out.println("Yes");
} else {
System.out.println("No");
}
But I can't seem to figure out how and where to put the specific meaning of each word that has been typed by the user in the edittext. Any help would be gladly appreciated. Thanks.
static String[] words = { "Cowboy", "animal", "monster" };
static String s = "My animal is a Cowboy";
static boolean check = false;
static String[] meanings = {"meaning1", "meaning2", "meaning3"};
static ArrayList<String> typed_words = new ArrayList<String>();
static ArrayList<String> typed_meanings = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
typed_words.add(words[i]);
typed_meanings.add(meanings[i]);
check = true;
} else {
}
}
if (check) {
System.out.println("Yes");
for(int i=0;i<typed_words.size();i++){
System.out.println("Word: "+typed_words.get(i)+" Meaning: "+typed_meanings.get(i));
}
} else {
System.out.println("No");
}
what about something like that?
int index;
...
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
index = i;
} else {
....
if (check) {
System.out.println(meanings[index]);
} else {
...
If the words and their meanings have the same relative positions in the two arrays then re-use the index i to print the corresponding meaning as well. But, the i would now have to be defined outside the loop so that it has a bigger scope now and is available inside the if check.
int i = 0
for (; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
break;
}
}
if (check) {
System.out.println("Meaning found: " + meanings[i]);
}
Since words and meanings arrays have the relative indexing, you can-
boolean check = false;
for (int i = 0; i < words.length; i++) {
if (s.equalsIgnoreCase(words[i])) { // We don't need "toLowerCase"
System.out.println("Word: " + words[i] + "\tMeaning: " + meanings[i]);
check = true;
break; // Match found; so get out of the loop
}
}
if(check){
System.out.println("Found!");
} else {
System.out.println("Not Found!");
}
Why not use a java.util.HashMapin which every word maps to a meaning?
String s = "";
HashMap<String,String> meaningMap = new HashMap<String,String>();
//just for the example
meaningMap.put("cowboy", "meaning1");
...
if (s.toLowerCase().contains(words[i].toLowerCase())) {
ouput = meaningMap.get(s);
}
...
System.out.println(s);
Another idea would be to use HashMap to store your data.
HashMap hm = new HashMap();
hm.put("cowboy", "meaning1");
hm.put("animal", "meaning2");
And then use
String s = yourEdittext.getText();
String[] words = s.split("\s+");
for (int i = 0; i < words.length(); i++) {
words[i] = words[i].replaceAll("[^\w]", "");
}
for (int i=0; i < words.length(); i++) {
if (hm.containsKey(words[i])) {
System.out.println("Meaning found: " + hm.get(words[i]));
}
}
This basically gets the sentece form the edittext, splits it into words then checks if each word is in the HashMap. This is good if your list of words is going to be quite big in comparison to the length of the sentence.
i would suggest that you make a Hashmap<String ,ArrayList<String>>
as you have more than one meaning for oneword.
so now just passing the word you need to find the meaning for.
you can.also use treemap if you need to store them in a sorted fashion.
so here's how you can find the meaning for a word .
ArrayList<String> meaning =map.get("cowboy");
for(String string : meaning ) {
Log.v("meaning",string);
}