java - Create a String from chars at indexes 0, 1, 4, 5, 8, 9 -
i have came across problem on codingbat.com:
given string, return string made of chars @ indexes 0,1, 4,5, 8,9 ... "kittens" yields "kien".
here code:
public string altpairs(string str) { string result = ""; (int = 0; < str.length(); i++) { result += str.substring(i, i+1); if (i > 0 && str.indexof(str.substring(i, i+1)) % 2 != 0) += 2; } return result; } for "codinghorror", should return "congrr".
- why code return "congrro" parameter "codinghorror"?
it solved in simpler way:
string result = ""; (int = 0; < str.length(); += 4) { result += str.substring(i, math.min(str.length(), + 2)); } return result; more:
- it's bad idea change counter variable inside for loop - use while loop then.
- substring(int beginindex, int endindex) - endindex exclusive.
Comments
Post a Comment