给定一个字符串,返回一个字符串,其中每个字符都是原始字符,有两个字符?

例如,我想向后打印每个字符串两次(字符串 - > ggnniirrttss)


import java.util.Scanner;

public class ReverseDoubleChar {

public static void main(String[] args) {


    Scanner input = new Scanner(System.in);

    System.out.println("Enter a string ");

    String str = input.nextLine();

    String new_str = "";


             String result = "";

    for (int i = 0; i < str.length(); i++) {

        result += str.substring(i, i + 1) + str.substring(i, i + 1);

        String result2 = null;

        result2 = result;

        System.out.println(result2);

        }

    }

}

然而,当我输入这个代码时,我得到的只是


ss

tt

rr

ii

nn

gg

全部在新线路上。有谁知道如何解决这个问题?谢谢


繁星coding
浏览 237回答 3
3回答

皈依舞

请参阅我更改的行上的评论:向后迭代字符串不要在每次循环迭代中打印每个双字符,因为您正在连接最终结果循环后打印最终结果import java.util.Scanner;public class ReverseDoubleChar {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("Enter a string ");String str = input.nextLine();String new_str = "";String result = "";for (int i = str.length() - 1; i >= 0; i--) { //Iterate through string backwards&nbsp; &nbsp; result += str.substring(i, i + 1) + str.substring(i, i + 1); //Concatenation&nbsp; &nbsp; String result2 = null;&nbsp; &nbsp; result2 = result;&nbsp; &nbsp; // System.out.println(result2); //Don't print each double char since you're concatenating above}System.out.println(result); //Print full double-charred string after loop}}输出:Enter a string&nbsp;stringggnniirrttss

qq_笑_17

使 for 循环向后迭代:String result = "";for (int i = str.length() - 1; i >= 0; i--) {&nbsp; &nbsp; String s = str.substring(i, i + 1);&nbsp; &nbsp; result += s + s;}System.out.println(result);或使用转发循环:String result = "";for (int i = 0; i < str.length(); i++) {&nbsp; &nbsp; String s = str.substring(i, i + 1);&nbsp; &nbsp; result = s + s + result;}System.out.println(result);

RISEBY

也许使用 StringBuilder 而不是做你自己的子字符串和连接。public class ReverseDoubleChar {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Scanner input = new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Enter a string ");&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder str = new StringBuilder(input.nextLine());&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder result = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = str.length() - 1; i >= 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append(str.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.append(str.charAt(i));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(result.toString());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java