简体   繁体   中英

How can I compare ArrayList and String ignoring case?

I'm solving this problem

My current working code is this:

// Importing the required packages.

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class AbbreviationsDriver {

// Main method.

    public static void main(String[] args) throws Exception {

        File abbreviationFile = new File("abbreviations.txt");
        Scanner scanFile = new Scanner(abbreviationFile);
        // ArrayList to save the messages in the file.
        ArrayList arrMessage = new ArrayList();
        String line;

        // read until last line
        while (scanFile.hasNextLine()) {
            line = scanFile.nextLine();
            arrMessage.add(line);
        }

        // Input File Name
        System.out.print(" Enter the name of the original file :");
        Scanner scanner = new Scanner(System.in);
        String inputFileName = scanner.next();

        // Output File Name
        System.out.print("\n Enter the name of the new file :");
        String outputFileName = scanner.next();

        Scanner scanInputFile = new Scanner(new File(inputFileName));
        PrintWriter out = new PrintWriter(new File(outputFileName));

        // Getting the line separator for the System.
        String newLine = System.getProperty("line.separator");

        while (scanInputFile.hasNextLine()) {
            String t;
            line = scanInputFile.nextLine();
            // Splitting on the basis of spaces.
            String[] temp = line.split(" ");
            // Adding the names to the ArrayList.
            for (int i = 0; i < temp.length; i++) {
                // if it is abbreviation, add <>
                if (arrMessage.contains(temp[i])) {
                    t = "<" + temp[i] + ">";
                }
                // if not, pass
                else {
                    t = temp[i];
                }
                // Write the string in the new file.
                out.write(t + " ");
            }
            // write new line
            out.write(newLine);
        }
        out.close();
    }
}

abbreviation.txt:

lol
:)
iirc
4
u
ttfn

sample_msg.txt

How are u today? Iirc, this is your first free day. Hope you are having fun! :)

but when I try my code,

How are <u> today? Iirc, this is your first free day. Hope you are having fun! <:)> 

Obviously, it did not filtered "Iirc" because it is capitalized. But, I want to check whether String is in ArrayList 'ignoring cases'. I searched inte.net, but I couldn't find the solution. How can I solve this problem?

List<T>.contains(T..) internally calls the "equals" method on T.

So your ArrayList contains will call the "equals" on String. That's why it's returning false when case doesnt match.

Several ways to deal with this:

  1. Change all strings of arrMessage to Uppercase/Lowercase and while comparing use temp[i].toUpperCase() or temp[i].toLowerCase()
  2. Create a wrapper around String and override the equals method to do equals ignore case.

edit: More on method 2

public class MyCustomStringWrapper {

  private String delegate;

  public MyCustomStringWrapper(String delegate) {
    this.delegate = delegate;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;
    MyCustomStringWrapper that = (MyCustomStringWrapper) o;
    return delegate.equalsIgnoreCase(that.delegate);
  }

  @Override
  public int hashCode() {
    return Objects.hash(delegate);
  }
}
public class AbbreviationsDriver {

// Main method.

    public static void main(String[] args) throws Exception {

        File abbreviationFile = new File("abbreviations.txt");
        Scanner scanFile = new Scanner(abbreviationFile);
        // ArrayList to save the messages in the file.
        List<MyCustomStringWrapper> arrMessage = new ArrayList();
        String line;

        // read until last line
        while (scanFile.hasNextLine()) {
            line = scanFile.nextLine();
            arrMessage.add(new MyCustomStringWrapper(line));
        }

        // Input File Name
        System.out.print(" Enter the name of the original file :");
        Scanner scanner = new Scanner(System.in);
        String inputFileName = scanner.next();

        // Output File Name
        System.out.print("\n Enter the name of the new file :");
        String outputFileName = scanner.next();

        Scanner scanInputFile = new Scanner(new File(inputFileName));
        PrintWriter out = new PrintWriter(new File(outputFileName));

        // Getting the line separator for the System.
        String newLine = System.getProperty("line.separator");

        while (scanInputFile.hasNextLine()) {
            String t;
            line = scanInputFile.nextLine();
            // Splitting on the basis of spaces.
            String[] temp = line.split(" ");
            // Adding the names to the ArrayList.
            for (int i = 0; i < temp.length; i++) {
                // if it is abbreviation, add <>
                if (arrMessage.contains(new MyCustomStringWrapper(temp[i]))) {
                    t = "<" + temp[i] + ">";
                }
                // if not, pass
                else {
                    t = temp[i];
                }
                // Write the string in the new file.
                out.write(t + " ");
            }
            // write new line
            out.write(newLine);
        }
        out.close();
    }
}

Edit: Ok so here is another issue with the input text/code.

The temp array is being created by splitting the sample_message by ' ' (space) ie it contains a string called "Iirc," and not "Iirc"

So you also need to change the sample_msg.txt file to this:

How are u today? Iirc , this is your first free day. Hope you are having fun! :)

Since you cant change the sample_msg.txt file, you can change the splitting logic like this:

String[] temp = line.split("(\\s|,\\s)");

which means split by space or (comma and space)

But then in the output b.txt you will loose the comma.

How are <u> today? <Iirc> this is your first free day. Hope you are having fun! <:)> 

Make all words in arrMessage small case:

// read until last line
while (scanFile.hasNextLine()) {
     line = scanFile.nextLine();
     arrMessage.add(line.toLowerCase());
}

While comparing, make your scanned word small case:

if (arrMessage.contains(temp[i].toLowerCase())) {

I'm solving this problem

My current working code is this:

// Importing the required packages.

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class AbbreviationsDriver {

// Main method.

    public static void main(String[] args) throws Exception {

        File abbreviationFile = new File("abbreviations.txt");
        Scanner scanFile = new Scanner(abbreviationFile);
        // ArrayList to save the messages in the file.
        ArrayList arrMessage = new ArrayList();
        String line;

        // read until last line
        while (scanFile.hasNextLine()) {
            line = scanFile.nextLine();
            arrMessage.add(line);
        }

        // Input File Name
        System.out.print(" Enter the name of the original file :");
        Scanner scanner = new Scanner(System.in);
        String inputFileName = scanner.next();

        // Output File Name
        System.out.print("\n Enter the name of the new file :");
        String outputFileName = scanner.next();

        Scanner scanInputFile = new Scanner(new File(inputFileName));
        PrintWriter out = new PrintWriter(new File(outputFileName));

        // Getting the line separator for the System.
        String newLine = System.getProperty("line.separator");

        while (scanInputFile.hasNextLine()) {
            String t;
            line = scanInputFile.nextLine();
            // Splitting on the basis of spaces.
            String[] temp = line.split(" ");
            // Adding the names to the ArrayList.
            for (int i = 0; i < temp.length; i++) {
                // if it is abbreviation, add <>
                if (arrMessage.contains(temp[i])) {
                    t = "<" + temp[i] + ">";
                }
                // if not, pass
                else {
                    t = temp[i];
                }
                // Write the string in the new file.
                out.write(t + " ");
            }
            // write new line
            out.write(newLine);
        }
        out.close();
    }
}

abbreviation.txt:

lol
:)
iirc
4
u
ttfn

sample_msg.txt

How are u today? Iirc, this is your first free day. Hope you are having fun! :)

but when I try my code,

How are <u> today? Iirc, this is your first free day. Hope you are having fun! <:)> 

Obviously, it did not filtered "Iirc" because it is capitalized. But, I want to check whether String is in ArrayList 'ignoring cases'. I searched internet, but I couldn't find the solution. How can I solve this problem?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM