简体   繁体   English

如何比较 ArrayList 和忽略大小写的字符串?

[英]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:缩写.txt:

lol
:)
iirc
4
u
ttfn

sample_msg.txt示例消息.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.显然,它没有过滤“IIrc”,因为它是大写的。 But, I want to check whether String is in ArrayList 'ignoring cases'.但是,我想检查 String 是否在 ArrayList '忽略大小写'中。 I searched inte.net, but I couldn't find the solution.我搜索了 inte.net,但找不到解决方案。 How can I solve this problem?我怎么解决这个问题?

List<T>.contains(T..) internally calls the "equals" method on T. List<T>.contains(T..)在内部调用 T 上的“equals”方法。

So your ArrayList contains will call the "equals" on String.所以你的 ArrayList 包含将调用字符串上的“等于”。 That's why it's returning false when case doesnt match.这就是为什么当大小写不匹配时它返回 false 的原因。

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()将 arrMessage 的所有字符串更改为大写/小写,并在比较时使用temp[i].toUpperCase() 或 temp[i].toLoweCase()
  2. Create a wrapper around String and override the equals method to do equals ignore case.String周围创建一个包装器并覆盖 equals 方法以执行 equals 忽略大小写。

edit: More on method 2编辑:更多关于方法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"临时数组是通过将 sample_message 拆分为“”(空格)来创建的,即它包含一个名为“Iirc”而不是“Iirc”的字符串

So you also need to change the sample_msg.txt file to this:因此,您还需要将 sample_msg.txt 文件更改为:

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:由于您无法更改 sample_msg.txt 文件,因此您可以像这样更改拆分逻辑:

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.但是随后在 output b.txt 中您将丢失逗号。

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

Make all words in arrMessage small case:将 arrMessage 中的所有单词设为小写:

// 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:缩写.txt:

lol
:)
iirc
4
u
ttfn

sample_msg.txt 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.显然,它没有过滤“Iirc”,因为它是大写的。 But, I want to check whether String is in ArrayList 'ignoring cases'.但是,我想检查 String 是否在 ArrayList '忽略大小写'中。 I searched internet, but I couldn't find the solution.我搜索了互联网,但找不到解决方案。 How can I solve this problem?我怎么解决这个问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想将arrayList对象与String进行比较,忽略大小写。 我怎样才能做到这一点? - I want to compare an arrayList object with a String, ignoring case. How can I do this? 如何在不区分大小写的情况下将arraylist与String进行比较? - how to compare arraylist with String whilst ignoring capitalization? 如何将字符串值与 Java 中字符串类型的 ArrayList 进行比较? - How can I compare String value with ArrayList of String type in Java? 我如何比较arraylist中的字符串与char类型的数组 - How can i compare a string in arraylist with char type of array 如何将字符串与arraylist比较 - How to compare string with arraylist 我如何对ArrayList进行排序 <ArrayList<String> &gt;? - How can I sort an ArrayList<ArrayList<String>>? 如何比较原始类型中的字符忽略大小写 - How to compare character ignoring case in primitive types 如何转换ArrayList <Object> 到ArrayList <String> 或ArrayList <Timestamp> ? - How can I convert ArrayList<Object> to ArrayList<String> or ArrayList<Timestamp>? 我如何比较 pdf 的 2 个版本并忽略页脚? - how can i compare 2 version of pdf and ignoring footer? 我如何使用 InCombiningDiacriticalMarks 忽略一种情况 - How I can use InCombiningDiacriticalMarks ignoring one case
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM