简体   繁体   中英

Storing and printing consecutive characters in a String?

the task is to store consecutive characters in a List. Main with Input/Output looks like this:

public static void main(String[] args) {
    List<String> blocks = blocks("Hello faaantastic world");
    System.out.println(blocks); // => ["ll", "aaa"]
    System.out.println(blocks("aaabccdeeeefaaa")); // => ["aaa", "cc", "eeee", "aaa"]
    System.out.println(blocks("This is an example")); // => []
    System.out.println(blocks("Another  example ...")); // => [" ", "..."]
    System.out.println(blocks("")); // => []

My method looks like this:

public static LinkedList<String> blocks(String s) {
    LinkedList<String> list = new LinkedList<>();
    String word = "";
    
    for(char c : s.toCharArray()) {
        if (c == ??) {
            
        }
    }
        
    return list;

the String word is used to store consecutive letters. I found the toCharArray, to split each character of the String. But I have a problem with the if-block. If I do c == c+1 to check I and the following character of I, it's not working...I don't know how to solve this problem. Can someone help me? trying to solve it for 2 days now...

There are other ways to write this code, but to fully use what you have done, just cache the prevChar so you can compare c with it. How to init prevChar is tricky, either to choose something not possible in the text, or add another bool variable to indicate you are working on the first char, or peek into the array to make sure prevChar is different from the 1st char.

In this case it may be preferable to use String::charAt method to retrieve characters in the input string and their comparing to previous character.

public static LinkedList<String> blocks(String s) {
    LinkedList<String> list = new LinkedList<>();

    String word = "" + s.charAt(0);
    
    for(int i = 1, n = s.length(); i < n; i++) {
        if (s.charAt(i) == s.charAt(i - 1)) {
            word += s.charAt(i);
        } else {
            if (word.length() > 1) {
                list.add(word);
            }
            word = "" + s.charAt(i);
        }
    }
    if (word.length() > 1) {
        list.add(word);
    }
        
    return list;
}

Test

System.out.println(blocks("Hello faaantastic worlddd"));

Output

[ll, aaa, ddd]

A shorter solution is possible using a regular expression to find repeating characters (.)\1+ :

public static List<String> findConsecutive(String s) {
    return Pattern.compile("(.)\\1+").matcher(s).results() // Stream<MatchResult>
        .map(mr -> mr.group(0)) // 0 group contains repeated characters
        .collect(Collectors.toList());
}

Test

System.out.println(findConsecutive("Hello   faaantastic worlddd"));

Output

[ll,    , aaa, ddd]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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