gpt4 book ai didi

java - 将大写字母移至字符串末尾

转载 作者:行者123 更新时间:2023-12-02 06:17:22 25 4
gpt4 key购买 nike

问题:给定一个字符串作为输入,将所有大写字母移动到字符串的末尾。示例:

move("Hello World")="ello orldHW"

问题是:我的代码没有在 ello orldHW 处停止,但它继续

ello orldHW // Expected output   
ello orldWH // What I am actually getting

代码:

public class MoveUppercaseChars {   
static String testcase1 = "Hello World";

public static void main(String args[]){
MoveUppercaseChars testInstance = new MoveUppercaseChars();
String result = testInstance.move(testcase1);
System.out.println("Result : "+result);
}

public String move(String str){
int len = str.length();
char ch;
for(int i=0; i<len; i++) {
ch = str.charAt(i);
if(((int)ch >= 65) && ((int)ch <= 90)) {
str = str.substring(0, i) + str.substring(i+1, len) + str.charAt(i);
}
}
return str;
}
}

最佳答案

分别存储小写字符和大写字符,然后返回两者的串联:

public class MoveUppercaseChars {   

static String testcase1 = "Hello World";

public static void main(String args[]){
MoveUppercaseChars testInstance = new MoveUppercaseChars();
String result = testInstance.move(testcase1);
System.out.println("Result : "+result);
}

public String move(String str){
int len = str.length();
String low = "";
String cap = "";
char ch;
for(int i=0; i<len; i++)
{
ch = str.charAt(i);
if(((int)ch >= 65) && ((int)ch <= 90))
{
cap += ch;
}
else {
low += ch;
}
}
return low + cap;
}
}

关于java - 将大写字母移至字符串末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com