猿问

如何跳过java字符串数组中的3个元素并获取下一个3个元素

我想获取由 3 个元素分隔的 Array 字符串。例如我需要跳过 3 个元素 0,1,2 并取 3,4,5 的元素。并重复。(跳过 6,7,8 并获得 9,10,11)直到数组结束。我该怎么做?


String s1[] = hh.split("\\r?\\n");

System.out.println(s1[3]);


for (int i=0;i<s1.length; i++){


}

子串输出:



            org.springframework

            spring-jdbc

            1.0-m4


            org.apache.tomcat

            tomcat-jdbc

            7.0.19


            commons-configuration

            commons-configuration

            20030311.152757


            commons-io

            commons-io

            0.1


            org.springframework.security.oauth

            spring-security-oauth2

            2.1.1.RELEASE


GCT1015
浏览 212回答 3
3回答

弑天下

使用模运算符和单个循环的解决方案。没有 IndexOutOfBounds 的风险。for (int i = 0; i < list.length; i++) {&nbsp; &nbsp; if (i % 6 > 2) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list[i]);&nbsp; &nbsp; }}i % 6 < 3如果您想要数组中每 6 个元素中的前 3 个,则可以将条件翻转为。编辑:以下内容接受您的输入并将其放入List<String[]>每个元素包含 3 行的位置。import java.nio.file.*;import java.util.stream.Stream;import java.util.*;import java.nio.charset.Charset;public class Partition2 {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String[] input = ...&nbsp; &nbsp; &nbsp; &nbsp; try (Stream<String> stream = Arrays.stream(input)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // https://stackoverflow.com/a/34759493/3717691&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] array = stream.map(line -> line.trim()).filter(line -> !line.isEmpty()).toArray(String[]::new);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<String[]> results = new ArrayList<String[]>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] tmp = new String[3];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp[i % 3] = array[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (i % 3 == 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; results.add(tmp);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tmp = new String[3];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

一只名叫tom的猫

for(int i=3;i<s1.length;i+=6){&nbsp; &nbsp;for(int j=0;j<3;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;s1[i+j]; // here is your element&nbsp; &nbsp; }}IndexOutOfBoundsException如果 arrag 大小不能被 6 整除,只需调整循环条件即可

杨__羊羊

您可以使用 Java 8 流。如果s有类型E:List<E> collect =&nbsp;&nbsp; &nbsp; IntStream.range(0, s.length) // 0...n-1&nbsp; &nbsp; &nbsp; &nbsp; .filter(i -> i/3%2 == 0) // g = i/3 is the number of the group and we take one group out of to (g % 2 == 0)&nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> s[i]) // take s[i]&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());
随时随地看视频慕课网APP

相关分类

Java
我要回答