Reputation: 25
I'm trying to get a function to take a String and change every 5th character to a 'z'
. For whatever reason the first character changed is always the 6th character and I can't figure out why. There's also an error if the string is divisible by 5, which is either because it starts on the 6th character or because my loop iteration goes one too far.
I've messed with the loop iteration but just can't see why it's starting on the 6th character.
public static String change5thPosition(String s) {
int fives = (int) Math.floor((s.length() / 5));
System.out.println(fives);
char[] chars = s.toCharArray();
for (int i = 0; i <= fives; i++) {
if (i != 0)
chars[i * 5] = 'z';
}
String returnString = new String(chars);
return returnString;
}
Input example:
all mimsy were the baragroves
Expected output:
all zimsyzwerezthe zbragzoves
Actual output:
all mzmsy zere zhe bzragrzves
Edit: Thanks for the help. here is my updated code:
public static String change5thPosition(String s) {
char[] chars = s.toCharArray();
for (int i = 4; i < s.length(); i = i + 5) {
chars[i] = 'z';
}
String returnString = new String(chars);
return returnString;
}
Upvotes: 0
Views: 776
Reputation: 72
You can try this code.
public class Simple {
public static void main(String args[]) {
System.out.println(change5thPosition("all mimsy were the baragroves"));
}
public static String change5thPosition(String s) {
int fives = (int) Math.floor((s.length() / 5));
System.out.println(fives);
char[] chars = s.toCharArray();
int index = 1;
StringBuilder myvar = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (index == 5) {
myvar.append("z");
index = 1;
} else {
myvar.append(c);
index++;
}
}
return myvar.toString();
}
}
Upvotes: 0
Reputation: 1316
A simple loop will do the Job. Take care of the index and avoid complex calculations.
String n = "all mimsy were the baragroves";
char[] s = n.toCharArray();
for(int i = 4;i<s.length;i+=5){
s[i]='z';
}
System.out.println(s);
Upvotes: 0
Reputation: 3138
Simply add a -1 to your index.
public static String change5thPosition(String s){
int fives = (int)Math.floor((s.length()/5));
System.out.println(fives);
char[] chars = s.toCharArray();
for(int i=0; i<=fives; i++){
if (i!=0)
chars[i*5 -1]='z';
}
String returnString = new String(chars);
return returnString;
}
Upvotes: 0
Reputation: 41261
Your code changes:
i=1 : chars[1 * 5 = 5]
i=2 : chars[2 * 5 = 10]
... and so on.
But since arrays are indexed starting with 0, you actually want to change the characters at 4,9,14, ...
.
So just subtract 1.
chars[i*5 - 1] = 'z';
These "off by one" errors are quite common in programming, and you'll learn to anticipate them.
On a side note, there's no need for:
for(int i=0; i<=fives; i++){
if (i!=0) {
...
}
}
... when you can just start i
at 1:
for(int i=1; i<=fives; i++){
...
}
You could also avoid having to multiply, by incrementing in fives:
for(int i=4, i < chars.length; i += 5) {
char[i] = 'z';
}
Upvotes: 4