Given a non-empty string and an int N, return the string made starting with char 0, and then every Nth char of the string. So if N is 3, use char 0, 3, 6, ... and so on. N is 1 or more.
everyNth("Miracle", 2) → "Mrce"
everyNth("abcdefg", 2) → "aceg"
everyNth("abcdefg", 3) → "adg"
This code isn't actually compiling. But after putting a couple of breakpoints and running in debug mode, it's showing it will return an ASCII value of "77" instead of a string value at the str.charAt()
position. I am not sure why. Please help.
I am trying to learn and understand the fundemental logic behind how to solve this problem.
I know you can use Stringbuilder
and append each value to buffer than print the values is one way getting the answer. So I want to avoid using any pre-defined classes, that will perform the logic in the background.
Attempt:
I've tried to convert the String
type to char
also, but same result.
public static String everyNth(String str, int n){
String charAtPosition = "";
int x = 0, pos = 0;
String finalString = "";
String stringPosition = str.charAt(pos); <-- Getting ASCII value instead of string value for ex. in "Miracle" string input, it should return "M"
charAtPosition = stringPosition * n;
for(int i = 0; i < str.length(); i++){
finalString = finalString + charAtPosition;
}
return finalString;
}