反转字符串的顺序 [英] Reversing the order of a string

查看:48
本文介绍了反转字符串的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对 Java 基本的工作原理仍然不了解,这是我写的一个方法,但不完全理解它是如何工作的,有人愿意解释吗?

So I'm still shaky on how basic java works, and here is a method I wrote but don't fully understand how it works anyone care to explain?

它应该采用 s 的值并以相反的顺序返回它.

It's supposed to take a value of s in and return it in its reverse order.

主要是 for 循环让我感到困惑.

Mainly the for loop is what is confusing me.

所以说我输入12345",我希望我的输出是54321"

So say I input "12345" I would want my output to be "54321"

Public string reverse(String s){
 String r = "";
 for(int i=0; i<s.length(); i++){
   r = s.charAt(i) + r;
}
  return r;
}

推荐答案

我们对 String a 的最后一个索引执行 for 循环, tha 索引 i 添加到 String s ,add 这里是一个连接:

We do a for loop to the last index of String a , add tha carater of index i to the String s , add here is a concatenation :

示例

String z="hello";
String x="world";

==> x+z="world hello" #不同于 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;
        }

这篇关于反转字符串的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆