繁体   English   中英

如何从Java中的字符串中删除字符串数组中除元素以外的所有内容?

[英]how do I remove everything except an element from an array of strings from a string in java?

我正在尝试从字符串中删除所有内容,除非它与字符串数组中的元素匹配。 我可以用单个字符来做到这一点。

char[] chars = {'1','2','3'};
  String foo = "abc123 foo !@#";
  String newFoo = "";
  for(int i = 0; i < foo.length(); i++){
     for(char c : chars){
        if(foo.charAt(i) == c){
           newFoo+=c;
        }
     }
  }

则newFoo将为“ 123”,因为除去了chars(1,2,3)数组中的所有其他字符,所有其他字符均已删除。 此代码将字符串foo删除,并删除所有不在char数组中的字符,并将字符串newFoo与其余字符合并。 这是该程序流程图的流程图

我正在寻找如何使用字符串数组而不是使用带有这些行代码的字符数组来做到这一点。

String[] strings = {"1","2","10"};
String foo = "1 2 3 4 5 6 7 8 9 10"
String newString = "";
//some code here

最后,newString将最终为“ 1210”。 我已经尝试了几个小时,但是还没有想出一个有效的代码来做到这一点,任何帮助将不胜感激。

这可能无法在所有情况下都有效,但是对于您发布的特定示例,我们可以使用下面的代码来实现您的结果。

基本上,我们将您的数组转换为List以访问contains()方法。 然后我们分割原始的foo字符串,以便我们可以检查原始数组中是否存在任何这些值。

import java.util.Arrays;
import java.util.List;

class Test {
    public static void main(String[] args) {

        String[] strings = {"1", "2", "10"};
        String foo = "1 2 3 4 5 6 7 8 9 10";

        // We'll use a StringBuilder for this
        StringBuilder newString = new StringBuilder();

        // First, we'll convert our strings array to a List so we have access to the [contains] method
        List<String> stringsList = Arrays.asList(strings);

        // Now, let's split foo into an array, using the space as a delimiter
        String[] foos = foo.split(" ");

        // Loop through each entry of foos and compare to each element in stringsList
        for (int i = 0; i < foos.length; i++) {

            if (stringsList.contains(foos[i])) {
                newString.append(foos[i]);
            }
        }

        System.out.println(newString);
    }
}


运行此示例将产生以下最终输出: 1210

这是我的解决方案:

    String[] chars = {"1","2","10"};
    //sort the array by length, so we check the longest string first.
    Arrays.sort(chars, (a,b)->b.length()-a.length());
    String foo = "1 2 3 4 5 6 7 8 9 10";
    String newFoo = "";
    for(int i = 0; i <= foo.length();){
        int j = i;
        for(String s : chars){
            if(foo.length() > i + s.length()){
                //find subString instead of character.
                String sub = foo.substring(i, i + s.length());
                if (sub.equals(s)) {
                    //move to the next index. Ex if 10 is at 0, next check start at 2
                    i += sub.length();
                    newFoo += sub;
                    break;
                }
            }
        }
        // check the index if it has been modified
        i = i == j ? ++j : i;
    }
    System.out.println(newFoo);

您可以尝试下面的代码。 如果要跳过重复项,可以使用Set

 String[] strings = {"1", "2", "10"};
String foo = "1 2 3 4 5 6 7 8 9 10".replaceAll("\\s","");

StringBuilder newString = new StringBuilder();

List<String> stringsList = Arrays.asList(strings);

//Set can be used to avoid duplicates like "1 1 2 2 4 4"
Set<String> resSet=new HashSet<String>();
// Loop through each entry of foos and compare to each element in stringsList
for (int i = 0; i < foo.length(); i++) {
    //if current char and next is 10 add it and continue
    if((String.valueOf(foo.charAt(i))+String.valueOf(foo.charAt(i+1))).equals("10") && stringsList.contains("10"))
    {
        resSet.add("10");

        //Extra operation in case you want to avoid duplication
        newString.append(10);
        i++;
        continue;
    }
    //if match found add it
    if (stringsList.contains(String.valueOf(foo.charAt(i)))) {
        newString.append(String.valueOf(foo.charAt(i)));

      //Extra operation in case you want to avoid duplication
        resSet.add(String.valueOf(foo.charAt(i)));
    }
}

System.out.println(newString);
System.out.println(resSet);

我将它们放入HashSet然后过滤掉该集中的字符。

// put in a nice hash set for speedy lookups.
Set<Character> chars = new HashSet(Arrays.asList('1','2','3'));

// method 1
String foo = "abc123 foo !@#";
String newFoo = "";
for(int i = 0; i < foo.length(); i++){
    char c = foo.charAt(i);
    if(!chars.contains(c)) {
        newFoo += c;
    }
}
System.out.println(newFoo);

// method 2
String result = foo.chars()
        .mapToObj(c -> (char)c)
        .filter(c -> !chars.contains(c))
        .map(c -> String.valueOf(c))
        .collect(Collectors.joining(""));
System.out.println("result is: "+result);

暂无
暂无

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

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