[英]java string reverse algorithm
I am trying to write my own string reverse algorithm (I know this already exists in java but I am doing this for education).我正在尝试编写自己的字符串反向算法(我知道这已经存在于 java 中,但我这样做是为了教育)。 The code below is what I have so far.
下面的代码是我到目前为止所拥有的。 It outputs only half the string reversed.
它只输出反转字符串的一半。 I have done some debugging and the reason is that it is changing stringChars2 at the same time as stringChars but I have no idea why that is happening as I am only trying to change stringChars .
我做了一些调试,原因是,它是在同一时间stringChars改变stringChars2,但我不知道这是为什么发生的事情,因为我只是想改变stringChars。 All help greatly appreciated.
非常感谢所有帮助。
EDIT my question was not "how to reverse a string" which has been asked before... but why my objects where changing without instruction, the answer below completely explains the problem.编辑我的问题不是之前问过的“如何反转字符串”......而是为什么我的对象在没有说明的情况下改变,下面的答案完全解释了这个问题。
public static void main(String[] args) {
//declare variables
Scanner input = new Scanner(System.in);
String myString = "";
int length = 0, index = 0, index2 = 0;
//get input string
System.out.print("Enter the string you want to reverse: ");
myString = input.next();
//find length of string
length = myString.length()-1;
index2 = length;
//convert to array
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
//loop through and reverse order
while (index<length) {
stringChars[index] = stringChars2[index2];
index++;
index2--;
}
//convert back to string
String newString = new String(stringChars);
//output result
System.out.println(newString);
//close resources
input.close();
}
char[] stringChars = myString.toCharArray();
char[] stringChars2 = stringChars;
On the second line you are assigning stringChars2
to the same object as stringChars
so basically they are one and the same and when you change the first you are changing the second as well.您所指定的第二行
stringChars2
为同一对象stringChars
所以基本上他们是同一个,当你改变你首先是改变第二也是如此。
Try something like this instead:试试这样的:
char[] stringChars = myString.toCharArray();
char[] stringChars2 = myString.toCharArray();
All that is not necessary.所有这些都是不必要的。 You can simply reverse a string with a for loop (in a method):
您可以简单地使用 for 循环反转字符串(在方法中):
public String reverseString(String str)
{
String output = "";
int len = str.length();
for(int k = 1; k <= str.length(); k++, len--)
{
output += str.substring(len-1,len);
}
return output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.