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

时间:2019-02-23 05:45:23

标签: java arrays string char

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

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与其余字符合并。 这是该程序的流程图 flow chart

我正在寻找如何使用字符串数组而不是使用带有这些行代码的字符数组来实现此功能。

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

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

4 个答案:

答案 0 :(得分:0)

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

基本上,我们将您的数组转换为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

答案 1 :(得分:0)

这是我的解决方案:

    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);

答案 2 :(得分:0)

您可以在下面尝试输入代码。如果要跳过重复项,可以使用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);

答案 3 :(得分:0)

我将它们放入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);