let's say I have a txt file containing:
john
dani
zack
the user will input a string, for example "omar" I want the program to search that txt file for the String "omar", if it doesn't exist, simply display "doesn't exist".
I tried the function String.endsWith() or String.startsWith(), but that of course displays "doesn't exist" 3 times.
I started java only 3 weeks ago, so I am a total newbie...please bear with me. thank you.
You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.
The hasNextLine() is a method of Java Scanner class which is used to check if there is another line in the input of this scanner. It returns true if it finds another line, otherwise returns false.
Just read this text file and put each word in to a List
and you can check whether that List
contains your word.
You can use Scanner scanner=new Scanner("FileNameWithPath");
to read file and you can try following to add words to List
.
List<String> list=new ArrayList<>();
while(scanner.hasNextLine()){
list.add(scanner.nextLine());
}
Then check your word is there or not
if(list.contains("yourWord")){
// found.
}else{
// not found
}
BTW you can search directly in file too.
while(scanner.hasNextLine()){
if("yourWord".equals(scanner.nextLine().trim())){
// found
break;
}else{
// not found
}
}
use String.contains(your search String)
instead of String.endsWith()
or String.startsWith()
eg
str.contains("omar");
You can go other way around. Instead of printing 'does not exist', print 'exists' if match is found while traversing the file and break; If entire file is traversed and no match was found, only then go ahead and display 'does not exist'.
Also, use String.contains()
in place of str.startsWith()
or str.endsWith()
. Contains check will search for a match in the entire string and not just at the start or end.
Hope it makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With