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;
}