猿问

我应该在这里使用哪种算法?在字符串数组中查找字符串

我有2个数组。


一个Array有字符串,我在找。


static String[] namesToLookFor = { "NR", "STAFFELNR", "VONDATUM"};

另一个Array有字符串,我是从* .csv文件中获得的。


indexString = indexReader.readLine();

indexArray = indexString.split(";");

我的目标是实现system.out.println() ,indexArray[]而不是的价值观namesToLookFor[]。


例如:


namesToLookFor = {"NR"};


indexArray = {"HELLO","NR"};



//Any Algorithm here...

因此,在这种情况下"HELLO"应将其打印出来,因为它不在namesToLookFor[]数组中。


POPMUISE
浏览 198回答 3
3回答

肥皂起泡泡

您可以遍历indexArray并检查每个元素是否包含在namesToLookFor数组中:&nbsp; &nbsp; String[] namesToLookFor = {"NR"};&nbsp; &nbsp; String[] indexArray = {"HELLO","NR"};&nbsp; &nbsp; List<String> excludedNames = Arrays.asList(namesToLookFor);&nbsp; &nbsp; for(String s : indexArray) {&nbsp; &nbsp; &nbsp; &nbsp; if (!excludedNames.contains(s)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }将仅输出“ HELLO”。

Smart猫小萌

如果您使用的是Java8,则可以执行以下操作List<String> list = Arrays.asList(namesToLookFor);Arrays.stream(indexArray)&nbsp; &nbsp; &nbsp; &nbsp; .filter(item -> !list.contains(item))&nbsp; &nbsp; &nbsp; &nbsp; .forEach(System.out::println);

侃侃尔雅

// Put array into set for better performanceSet<String> namesToFilter = new HashSet<>(Arrays.asList("NR", "STAFFELNR"));String[] indexArray = indexReader.readLine().split(";");// Create list with unfiltered values and remove unwanted onesList<String> resultList = new ArrayList<>(indexArray);resultList.removeAll(namesToFilter);// Do with result whatever you wantfor (String s : resultList)&nbsp; &nbsp; System.out.println(s);
随时随地看视频慕课网APP

相关分类

Java
我要回答