Java 在 ArrayList 中搜索字符串中的某个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18036819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:57:34  来源:igfitidea点击:

Search ArrayList for certain character in string

javaarrayssearcharraylistreplace

提问by InDeep

What is the correct syntax for searching an ArrayListof strings for a single character? I want to check each string in the array for a single character. Ultimately I want to perform multiple search and replaces on all strings in an array based on the presence of a single character in the string. I have reviewed java-examples.com and java docs as well as several methods of searching ArrayLists. None of them do quite what I need. P.S. Any pointers on using some sort of file library to perform multiple search and replaces would be great.

搜索ArrayList单个字符的字符串的正确语法是什么?我想检查数组中的每个字符串是否有单个字符。最终,我想根据字符串中单个字符的存在对数组中的所有字符串执行多次搜索和替换。我已经查看了 java-examples.com 和 java 文档以及搜索 ArrayList 的几种方法。他们都没有做我需要的。PS任何关于使用某种文件库来执行多次搜索和替换的指针都会很棒。

--- Edit ---

- - 编辑 - -

As per MightyPork's recommendations arraylistrevised to use simple stringtype. This also made it compatible with hoosssein's solution which is included.

根据 MightyPork 的建议arraylist修改为使用简单string类型。这也使它与包含的 hoosssein 的解决方案兼容。



public void ArrayInput() {
    String FileName;                            // set file variable
    FileName = fileName.getText();              // get file name

    ArrayList<String> fileContents = new ArrayList<String>();       // create arraylist

    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
        String line = null;

        while ((line = reader.readLine()) != null) {
            if(line.length() > 0) {                         // don't include blank lines
                line = line.trim();                         // remove whitespaces
                fileContents.add(line);                     // add to array
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }

        String oldstr;
        String newstr;

        oldstr = "}";
        newstr = "!!!!!";

        for(int i = 0; i < fileContents.size(); i++) {
            if(fileContents.contains(oldstr)) {
                fileContents.set(i, fileContents.get(i).replace(oldstr, newstr));
            }
        }   

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }
                                // close file
    }

    catch (IOException ex) {    // E.H. for try
        JOptionPane.showMessageDialog(null, "File not found.  Check name and directory.");
    }           
}

采纳答案by Hossein Nasr

first you need to iterate the list and search for that character

首先,您需要迭代列表并搜索该字符

string.contains("A");

for replacing the character you need to keep in mind that String is immutable and you must replace new string with old string in that list

要替换字符,您需要记住 String 是不可变的,您必须用该列表中的旧字符串替换新字符串

so the code is like this

所以代码是这样的

public void replace(ArrayList<String> toSearchIn,String oldstr, String newStr ){
    for(int i=0;i<toSearchIn.size();i++){
        if(toSearchIn.contains(oldstr)){
            toSearchIn.set(i, toSearchIn.get(i).replace(oldstr, newStr));
        }
    }
}

回答by MightyPork

You can try this, modify as needed:

你可以试试这个,根据需要修改:

public static ArrayList<String> findInString(String needle, List<String> haystack) {
    ArrayList<String> found = new ArrayList<String>();

    for(String s : haystack) {
        if(s.contains(needle)) {
            found.add(s);
        }
    }

    return found;
}

(to search char, just do myChar+""and you have string)

(要搜索字符,只需执行即可myChar+""获得字符串)



To add the find'n'replace functionality should now be fairly easy for you.

添加 find'n'replace 功能现在对您来说应该相当容易。



Here's a variant for searching String[]:

这是搜索的变体String[]

public static ArrayList<String[]> findInString(String needle, List<String[]> haystack) {
    ArrayList<String[]> found = new ArrayList<String[]>();

    for(String fileLines[] : haystack) {
        for(String s : fileLines) {
            if(s.contains(needle)) {
                found.add(fileLines);
                break;
            }
        }
    }

    return found;
}

回答by arynaq

For the search and replace you are better off using a dictionary, if you know that you will replace Hiwith Hello. The first one is a simple search, here with the index and the string being returned in a Object[2], you will have to cast the result. It returns the first match, you were not clear on this.

对于搜索和替换,最好使用字典,如果您知道将替换HiHello. 第一个是简单的搜索,这里的索引和字符串在 Object[2] 中返回,您必须转换结果。它返回第一场比赛,您对此不清楚。

public static Object[] findStringMatchingCharacter(List<String> list,
        char character) {

    if (list == null)
        return null;
    Object[] ret = new Object[2];
    for (int i = 0; i < list.size(); i++) {
        String s = list.get(i);
        if (s.contains("" + character)) {
            ret[0] = s;
            ret[1] = i;
        }
                    return ret;
    } 
    return null;
}

public static void searchAndReplace(ArrayList<String> original,
        Map<String, String> dictionary) {
    if (original == null || dictionary == null)
        return;
    for (int i = 0; i < original.size(); i++) {
        String s = original.get(i);
        if (dictionary.get(s) != null)
            original.set(i, dictionary.get(s));
    }
}

回答by Naman

Another way by using iterator

使用迭代器的另一种方式

public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Naman");
        list.add("Aman");
        list.add("Nikhil");
        list.add("Adarsh");
        list.add("Shiva");
        list.add("Namit");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (next.startsWith("Na")) {
                System.out.println(next);
            }
        }
    }

回答by Luk

You don't need to iterate over lines twice to do what you need. You can make replacement when iterating over file.

你不需要重复行两次来做你需要的。您可以在迭代文件时进行替换。

Java 8 solution

Java 8 解决方案

 try (BufferedReader reader = Files.newBufferedReader(Paths.get("pom.xml"))) {
        reader
            .lines()
            .filter(x -> x.length() > 0)
            .map(x -> x.trim())
            .map(x -> x.replace("a", "b"))
            .forEach(System.out::println);
    } catch (IOException e){
        //handle exception
    }