gpt4 book ai didi

java - 如何在没有任何复杂路由的情况下更改字符串?

转载 作者:行者123 更新时间:2023-12-04 10:29:20 24 4
gpt4 key购买 nike

这是我为了完成我的其他项目而创建的代码。我已经尝试了一段时间,并且我认为如果循环中声明的变量太多,则不会访问循环中的深度,因此我认为我无法通过任何简单的方法来完成此操作。如果有人能告诉我为什么这段代码没有给我我希望的结果,那将会非常有帮助。

        char letter, D;
int lengthString, position, positionInCat, textLength, repetitions;
String cat = "cat", newCat = "", text, reversingText, reversedText = ""; //Goal: change "cat" to "cad"

D = 'D';
lengthString = cat.length();
position = 0;
positionInCat = 2; // what I am looking to alter. For example
//position in cat = 2. 2 becomes a D or any other character. The output should //be: cDt

reversingText = cat;
repetitions = reversingText.length();
textLength = reversingText.length() - 1;

while (repetitions > 0) { // reverses the text
letter = reversingText.charAt(textLength);
reversedText = reversedText + letter;
repetitions--;
textLength --;
}
letter = ' ';
cat = reversedText; // applies the reversion
while (lengthString > 1) {
while (lengthString != positionInCat) { // changes cat to what I want the outcome to be: cDt
letter = cat.charAt(position);
newCat = newCat + letter; // rebuilding CAT
position++;
lengthString--;
}
newCat = newCat + D; // Altering the cat
position++;
lengthString--;
while (lengthString > 0) {
letter = cat.charAt(position);
newCat = newCat + letter;
position++;
lengthString--;
} }
letter = ' ';
cat = newCat;
reversingText = cat; // giving the reversingText its work
repetitions = reversingText.length();
textLength = reversingText.length() - 1;

while (repetitions > 0) { // unreverses the reversed text
letter = reversingText.charAt(textLength);
reversedText = reversedText + letter;
repetitions--;
textLength --;
}
cat = reversedText; // applies the reversion

System.out.print(cat); // what my work should have given me is cDt







}

} // This is my attempt at it, but I can only get out "taccDt" with it, instead of "cDt"

最佳答案

Java 为您提供内置 String操纵方法。

catcDt您可以使用 StringBuilder .如果您知道索引,则 StringBuilder 可以轻松帮助您替换字符串中的单个字符。

StringBuilder stringBuilder = new StringBuilder("cat");
stringBuilder.setCharAt(1, 'D');
System.out.println(stringBuilder.toString()); //Prints cDt

由于索引是基于 0 的,因此第一个字符 'c' 位于索引 0 处,第二个字符 'a' 位于索引 1 处。

关于java - 如何在没有任何复杂路由的情况下更改字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60477743/

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