1

I've currently got a large text file with lots of the most popular names. I get the user to input a specific name and I'm currently trying to print the line that has the name. My problem is that if the user enters a name like Alex, every name that contains Alex like Alexander, Alexis, Alexia gets printed when I only want Alex to get printed. What can I do to "if(line.contains(name)){" to fix this. The line contains info like the name, it's popularity ranking and number of people with that name

    try {
            line = reader.readLine(); 
            while (line != null) {
                if(line.contains(name)){
                    text += line;
                    line = reader.readLine();
                }
                line = reader.readLine();
            }
        }catch(Exception e){
            System.out.println("Error");
        }

        System.out.println(text);
Workkkkk
  • 265
  • 1
  • 5
  • 22

3 Answers3

2

You can use regex with a word boundary for this task:

final String regex = String.format("\\b%s\\b", name);

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(line);
matcher.find();
if( matcher.group(0).length() > 0 ) {
    text += line;
    line = reader.readLine();
}
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
2

A shorthand would be to use Java8 Streams: Here is a look :

public class Test2 {

    public static void main(String[] args) {
        String fileName = "c://lines.txt";
        String name = "nametosearch";

        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

            stream.filter(line -> line.contains(" " + name + " ")).forEach(System.out::println);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Shailesh Pratapwar
  • 4,054
  • 3
  • 35
  • 46
1

line.equals(name)

Replace

line.contains(name)

Tangoo
  • 1,329
  • 4
  • 14
  • 34
  • Sorry, forgot to mention that there is other info on the line like the name's popularity ranking and number of people with that name. .equals wouldnt work – Workkkkk Apr 04 '18 at 03:10
  • 2
    Ok, please take the answer of @Aniket Sahrawat, or maybe you can split the line into string array, and take the first element to compare with the input. – Tangoo Apr 04 '18 at 03:13