1

Given a string, how can I take each pair of letters ?

Here is an example, given string = "asdfg", the code outputs arr[as,df,g_]; given string = "asdfgghk", the code outputs arr[as,df,gg,hk].

If the string length is odd then the last pair will be the char[i]_, (underscore)

Here is part of the code I wrote:


    public static char
    getCharFromString(String s, int index) 
    { 
        return s.charAt(index); 
    } 
    public static String[] solution(String s) {
        char a, b;
        String[] arr = new String[(s.length() / 2)];
        for(int i = 0; i < s.length(); i+=2) {
            if(s.length() % 2 == 0) {
                 a = getCharFromString(s, i);
                 b = getCharFromString(s, i + 1);
                arr[i] = a + b ;
            }
            else {
                a = getCharFromString(s, i);
                b = getCharFromString(s, i + 1);
                arr[i] = a + b ;
                if(i == s.length()) {
                    b = "_";
                }   
            }
        }
        return arr;
    }

Gil Caplan
  • 64
  • 8
  • Welcome to Stack Overflow! Please read "How to create a [mcve]". Then use the [edit] link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Meaning: dont just give us your assignment and your current code. Dont expect us to first figure what your code is currently doing, to then find out where exactly it is wrong and leading to wrong output. – GhostCat Nov 02 '20 at 10:22
  • And unrelated: learn about java naming conventions. Class names always go UpperCase. And the names you are using in your code should be meaningful. "code" doesnt tell you what that class is supposed to do, and s, a, b, ... tell you nothing about the *purpose* of the variables. Only use single char names for loop indexes, anything else deserves a more lengthy, telling name! – GhostCat Nov 02 '20 at 10:23

2 Answers2

1

One of many solutions:

public static String[] solution(String s) {
    int arrayLen = s.isEmpty() ? 1 : (int) Math.ceil(s.length() / 2.0);
    String[] arr = new String[arrayLen];

    for (int i = 0; i < arrayLen; i++) {
        arr[i] = s.substring(Math.min(s.length(), i * 2), Math.min(s.length(), i * 2 + 2));
    }
    if (arr[arrayLen - 1].length() == 1) {
        arr[arrayLen - 1] = arr[arrayLen - 1] + "_";
    } else if (arr[arrayLen - 1].isEmpty()){
        arr[arrayLen - 1] = "__";
    }

    return arr;
}
Mateusz
  • 353
  • 2
  • 15
1

It is quite easy using a regex. Simply split the string on every 2 characters and if the last element of the array is short of one character, append _ to it.

Demo:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(Arrays.toString(solution("asdfg")));
        System.out.println(Arrays.toString(solution("asdfgghk")));
    }

    public static String[] solution(String s) {
        // Split the string on every 2 characters
        String[] arr = s.split("(?<=\\G..)");

        // If the last element of the array is short of one character, append '_' to it
        if (arr.length > 1 && arr[arr.length - 1].length() != 2) {
            arr[arr.length - 1] += "_";
        }
        return arr;
    }
}

Output:

[as, df, g_]
[as, df, gg, hk]

Note: The regex, (?<=\\G..) has been explained below:

  1. \G asserts position at the end of the previous match or the start of the string for the first match
  2. . matches any character (except for line terminators)
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110