因此,我仍然对基本Java的工作方式不满意,这是我编写的一种方法,但是还没有完全理解它的工作原理,有人在乎解释吗?
应该采用s的值,并以相反的顺序返回它。
编辑:主要是for循环是什么让我感到困惑。
假设我输入“ 12345”,我希望输出为“ 54321”
Public string reverse(String s){
String r = "";
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r;
}
return r;
}
我们对字符串a的最后一个索引执行一个for循环,将索引i的carater添加到String s,这里添加一个串联:
例
String z="hello";
String x="world";
==> x+z="world hello" #different to z+x ="hello world"
对于您的情况:
String s="";
String a="1234";
s=a.charAt(0)+s ==> s= "1" + "" = "1" ( + : concatenation )
s=a.charAt(1)+s ==> s='2'+"1" = "21" ( + : concatenation )
s=a.charAt(2)+s ==> s='3'+"21" = "321" ( + : concatenation )
s=a.charAt(3)+s ==> s='3'+"321" = "4321" ( + : concatenation )
等等..
public String reverse(String s){
String r = ""; //this is the ouput , initialized to " "
for(int i=0; i<s.length(); i++){
r = s.charAt(i) + r; //add to String r , the caracter of index i
}
return r;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句