Reputation: 331
I'm using a txt file as database and I want to search the contents of file for specific string(word), and if exists to add it on a listview. I've manage to achive the most part using the above code:
Read the file
public String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.words);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
Trying to search for string
if(readTxt().contains(word)){
addWord.add(new String(word));
The problem is that I cannot search for whole words. If I use the above way, I get everything contains string' s characters. For e.g if the word is LETTER, I get a match, but I also get a match if the word is TTE. I've search here and tried some different approaches which discribed but nothing worked.
Upvotes: 0
Views: 740
Reputation: 12823
Use a regular expression pattern matcher to match whole words. This one splits a message into 160 character chunks, but you can easily modify it to find a "whole word".
protected ArrayList<String> splitMsg(SmsMessage smsMessage) {
ArrayList<String> smt;
Pattern p = Pattern.compile(".{1,160}");
Matcher regexMatcher = p.matcher(smsMessage.getMsgBody());
smt = new ArrayList<String>();
while (regexMatcher.find()) {
smt.add(regexMatcher.group());
}
return smt;
}
Upvotes: 0