'Create a String from chars at indexes 0, 1, 4, 5, 8, 9
I have came across this problem on codingbat.com:
Given a string, return a string made of the chars at indexes 0,1, 4,5, 8,9 ... so "kittens" yields "kien".
Here is my code:
public String altPairs(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
result += str.substring(i, i+1);
if (i > 0 && str.indexOf(str.substring(i, i+1)) % 2 != 0) i += 2;
}
return result;
}
For "CodingHorror", it should return "Congrr".
- Why does my code return "Congrro" for the parameter "CodingHorror"?
Solution 1:[1]
First the second index of substring is exclusive. If you want 2 characters directly, you should use i+2 instead of i+1:
str.substring(i, i+2)
Then, you just have to increment i by 4 at each loop turn. Use i+=4 instead of i++, and you won't need the conditional increment.
for (int i = 0; i < str.length() - 1; i+=4) {
result += str.substring(i, i+2);
}
Or, if you allow to break a pair of characters at the end of the String:
for (int i = 0; i < str.length(); i+=4) {
if (i < str.length() - 1)
result += str.substring(i, i+2);
else
result += str.substring(i, i+1);
}
Solution 2:[2]
public String altPairs(String str) {
String newStr = "";
for(int i=0;i<str.length();i++)
{
newStr = newStr +str.charAt(i);
if(i%2!=0)
i=i+2;
}
return newStr;
}
I did it this way Inside loop add a condition if i is odd then i=i+2; which is increasing the value of i to +3 index
Solution 3:[3]
check this out..
public String altPairs(String str) {
String result = "";
for (int i = 0; i < str.length(); ) {
result += str.substring(i, i+1);
i+=4;
}
return result;}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Aditya Kumar |
| Solution 3 | DCoder |
