英文:
Returning a string made by odd index number of the string
问题
public class MeWhileLoop
{
public int a, b;
public String str;
public String OddNumChar(){
int index = 0;
str = "Poland";
String result = ""; // Initialize an empty string to store the result
while(index < str.length()){
if(index % 2 != 0){ // Check if the index is odd
result += str.substring(index, index+1); // Append the odd-indexed character to the result
}
index++;
}
return result; // Return the string containing odd-indexed characters
}
}
英文:
The Return type is a String and no Input parameters. I have to go through the instance variable called str and return a string that is put together by odd index number of the string.
i forgot to mention that it has to be a while loop
Example: str = "Poland"
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.
I so far have come up with this
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;
}
}
I'm just stuck because the index+1 won't take out the odd letters or any letter at all and I have no clue why.
答案1
得分: 3
以下是翻译好的内容:
第一段代码:
如何考虑:
String res = "";
// 从第二个字符开始,然后每次增加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;
英文:
How about:
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;
This might have better performance for larger strings:
StringBuilder sb = new StringBuilder(str.length() / 2);
for (int i = 1; i < str.length(); i += 2) {
sb.append(str.charAt(i));
}
return sb.toString();
If you really need while loop for some reason:
String res = "";
int i = 1;
while (i < str.length()) {
res += str.charAt(i);
i += 2;
}
return res;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论