kensil
kensil

Reputation: 136

add every Nth character to string

The task is to get every nth character and put it in a string. I got this problem halfway solved.

If Miracle is the string typed in and the int = 2, i will get the following output: "Mrc", while it should be "Mrce".

Why is it missing out on the last character? The logic part seems reasonable to me.

public String everyNth(String str, int n) {
  String firstletter = str.substring(0,1); // We store the first letter as well.
  String secondhalf = "";
  while(str.length() > n) { // Run as long as n reaches the end of the string.
    secondhalf += str.substring(n, n+1); // Add Nth character to string.
    n+=n;
  }
  return firstletter+secondhalf;
}

EDIT: Added a separate counter, int counter = n; so it doesnt double the value all the time.

Upvotes: 0

Views: 3750

Answers (2)

MQ87
MQ87

Reputation: 1058

I would use charAt function in a for to do it:

public String everyNth(String str, int n) {
  String result="";
  for(i=0; i<str.length(); i=i+n){
    result+=str.charAt(i);
  }
  return result;
}

Upvotes: 1

DontRelaX
DontRelaX

Reputation: 754

Your problem here:

n+=n;

first time it 2, then 4, then 8...

Just use separate counter.

Upvotes: 3

Related Questions