If I have this string
String str="characters";
the result would like following
result="caatr";
what I have done is selecting char by char from the given string until we get the result. The chars are selected at indices which are multiples of given n. Example: if n=2, the relevant indices to be selected are 0, 2, 4 ... and for n = 3, the indices are 0, 3, 6...
I have solved it in two ways and are almost the same but is there any other ways?
char[] arr = str.toCharArray();
String s="";
for(int i=0;i<str.length();i=i+n)
s=s+arr[i]+"";
the other one is
String result = "";
for (int i=0; i<str.length(); i = i + n)
result = result + str.charAt(i);
public static void main(String args[]) {
System.out.println(getResultOf("characters"));
}
private static String getResultOf(String input) {
boolean skip = false;
StringBuilder sb = new StringBuilder();
for (char ch : input.toCharArray()) {
if (!skip) {
sb.append(ch);
}
skip = !skip;
}
return sb.toString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.