返回由字符串的奇数索引号组成的字符串
Returning a string made by odd index number of the string
Return 类型是字符串,没有输入参数。我必须通过名为 str 的实例变量和 return 一个由字符串的奇数索引号组合在一起的字符串。
我忘了说它必须是一个 while 循环
示例:str = "波兰"
then the method should return "oad" because P is an even number, o is odd, l is even, a is odd, n is even, d is odd.
到目前为止我已经想到了这个
public class MeWhileLoop
{
public int a, b;
public String str;
public String OddNumChar(){
int index = 0;
str = "Poland";
while(index < str.length()){
System.out.println(str.substring(index, index+1));
index++;
}
System.out.println();
return str;
}
}
我被卡住了,因为 index+1 根本不会去掉奇数字母或任何字母,我不知道为什么。
怎么样:
String res = "";
// start at second character and then increment by 2
for (int i = 1; i < str.length(); i += 2) {
res += str.charAt(i);
}
return res;
对于较大的字符串,这可能会有更好的性能:
StringBuilder sb = new StringBuilder(str.length() / 2);
for (int i = 1; i < str.length(); i += 2) {
sb.append(str.charAt(i));
}
return sb.toString();
如果您出于某种原因确实需要 while 循环:
String res = "";
int i = 1;
while (i < str.length()) {
res += str.charAt(i);
i += 2;
}
return res;
Return 类型是字符串,没有输入参数。我必须通过名为 str 的实例变量和 return 一个由字符串的奇数索引号组合在一起的字符串。
我忘了说它必须是一个 while 循环
示例:str = "波兰"
then the method should return "oad" because P is an even number, o is odd, l is even, a is odd, n is even, d is odd.
到目前为止我已经想到了这个
public class MeWhileLoop
{
public int a, b;
public String str;
public String OddNumChar(){
int index = 0;
str = "Poland";
while(index < str.length()){
System.out.println(str.substring(index, index+1));
index++;
}
System.out.println();
return str;
}
}
我被卡住了,因为 index+1 根本不会去掉奇数字母或任何字母,我不知道为什么。
怎么样:
String res = "";
// start at second character and then increment by 2
for (int i = 1; i < str.length(); i += 2) {
res += str.charAt(i);
}
return res;
对于较大的字符串,这可能会有更好的性能:
StringBuilder sb = new StringBuilder(str.length() / 2);
for (int i = 1; i < str.length(); i += 2) {
sb.append(str.charAt(i));
}
return sb.toString();
如果您出于某种原因确实需要 while 循环:
String res = "";
int i = 1;
while (i < str.length()) {
res += str.charAt(i);
i += 2;
}
return res;