Program Club

n 번째 문자마다 문자열 분할

proclub 2020. 11. 2. 20:05
반응형

n 번째 문자마다 문자열 분할


JavaScript에서 이것은 3 번째 문자마다 문자열을 분할하는 방법입니다.

"foobarspam".match(/.{1,3}/g)

Java에서 이것을 수행하는 방법을 알아 내려고 노력하고 있습니다. 포인터가 있습니까?


다음과 같이 할 수 있습니다.

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));

다음을 생성합니다.

[123, 456, 789, 0]

정규식은 (?<=\G...)이 빈 문자열과 일치하는 마지막 경기 ( \G다음) 세 개의 문자 ( ...) 전에 (그것을 (?<= ))


Java는 완전한 기능을 갖춘 분할 유틸리티를 제공하지 않으므로 Guava 라이브러리 는 다음을 수행합니다.

Iterable<String> pieces = Splitter.fixedLength(3).split(string);

Splitter 용 Javadoc을 확인하십시오 . 매우 강력합니다.


import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        for (String part : getParts("foobarspam", 3)) {
            System.out.println(part);
        }
    }
    private static List<String> getParts(String string, int partitionSize) {
        List<String> parts = new ArrayList<String>();
        int len = string.length();
        for (int i=0; i<len; i+=partitionSize)
        {
            parts.add(string.substring(i, Math.min(len, i + partitionSize)));
        }
        return parts;
    }
}

Bart Kiers 답변 외에도 동일한 의미를 가진 ...세 문자를 나타내는 정규식 표현식에서 세 개의 점을 사용하는 대신 가능하다는 것을 추가하고 싶습니다 .{3}.

그러면 코드는 다음과 같습니다.

String bitstream = "00101010001001010100101010100101010101001010100001010101010010101";
System.out.println(java.util.Arrays.toString(bitstream.split("(?<=\\G.{3})")));

이를 통해 문자열 길이를 수정하는 것이 더 쉬울 것이며 이제 가변 입력 문자열 길이로 함수 생성이 합리적입니다. 이것은 다음과 같이 수행 될 수 있습니다.

public static String[] splitAfterNChars(String input, int splitLen){
    return input.split(String.format("(?<=\\G.{%1$d})", splitLen));
}

IdeOne의 예 : http://ideone.com/rNlTj5


늦은 입장.

다음은 하나의 라이너 인 Java8 스트림을 사용하는 간결한 구현입니다.

String foobarspam = "foobarspam";
AtomicInteger splitCounter = new AtomicInteger(0);
Collection<String> splittedStrings = foobarspam
                                    .chars()
                                    .mapToObj(_char -> String.valueOf((char)_char))
                                    .collect(Collectors.groupingBy(stringChar -> splitCounter.getAndIncrement() / 3
                                                                ,Collectors.joining()))
                                    .values();

산출:

[foo, bar, spa, m]

이것은 늦은 대답이지만 어쨌든 새로운 프로그래머가 볼 수 있도록 그것을 공개하고 있습니다.

정규 표현식을 사용하려면 원하지 않는 경우 타사 라이브러리에 의존하지 않으려면, 당신은 사이 걸리는 대신이 방법을 사용할 수 있습니다 89,920100,113 A의 나노초 2.80 GHz의 CPU (밀리 초 미만). Simon Nickerson의 예만큼 예쁘지는 않지만 작동합니다.

   /**
     * Divides the given string into substrings each consisting of the provided
     * length(s).
     * 
     * @param string
     *            the string to split.
     * @param defaultLength
     *            the default length used for any extra substrings. If set to
     *            <code>0</code>, the last substring will start at the sum of
     *            <code>lengths</code> and end at the end of <code>string</code>.
     * @param lengths
     *            the lengths of each substring in order. If any substring is not
     *            provided a length, it will use <code>defaultLength</code>.
     * @return the array of strings computed by splitting this string into the given
     *         substring lengths.
     */
    public static String[] divideString(String string, int defaultLength, int... lengths) {
        java.util.ArrayList<String> parts = new java.util.ArrayList<String>();

        if (lengths.length == 0) {
            parts.add(string.substring(0, defaultLength));
            string = string.substring(defaultLength);
            while (string.length() > 0) {
                if (string.length() < defaultLength) {
                    parts.add(string);
                    break;
                }
                parts.add(string.substring(0, defaultLength));
                string = string.substring(defaultLength);
            }
        } else {
            for (int i = 0, temp; i < lengths.length; i++) {
                temp = lengths[i];
                if (string.length() < temp) {
                    parts.add(string);
                    break;
                }
                parts.add(string.substring(0, temp));
                string = string.substring(temp);
            }
            while (string.length() > 0) {
                if (string.length() < defaultLength || defaultLength <= 0) {
                    parts.add(string);
                    break;
                }
                parts.add(string.substring(0, defaultLength));
                string = string.substring(defaultLength);
            }
        }

        return parts.toArray(new String[parts.size()]);
    }

n 번째 문자마다 문자열을 분할하여 List의 각 인덱스에 넣을 수도 있습니다.

여기에 Sequence라는 문자열 목록을 만들었습니다.

목록 <문자열> 시퀀스

그런 다음 기본적으로 문자열 "KILOSO"를 2 단어마다 분할합니다. 따라서 'KI' 'LO' 'SO'는 Sequence라는 목록의 별도 색인에 통합됩니다.

문자열 S = KILOSO

Sequence = Arrays.asList (S.split ( "(? <= \ G ..)"));

그래서 내가 할 때 :

System.out.print(Sequence)

It should print :

[KI, LO, SO]

to verify I can write :

System.out.print(Sequence.get(1))

it will print :

LO

참고URL : https://stackoverflow.com/questions/2297347/splitting-a-string-at-every-n-th-character

반응형