Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:反转字符串,但保留逗号的索引_Java_String - Fatal编程技术网

Java:反转字符串,但保留逗号的索引

Java:反转字符串,但保留逗号的索引,java,string,Java,String,在保留逗号索引的同时反转字符串 需要反转的字符串:“T,he,quick,bro,wn f,ox jump,s over,the l,azy do,g” 预期输出:“g、od、yzal、eht、revo、spmuj、xof nw、orb kc、iuq eh、T”这是您可以使用的代码 String original = "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g"; String reverse = original.re

在保留逗号索引的同时反转字符串

需要反转的字符串:“T,he,quick,bro,wn f,ox jump,s over,the l,azy do,g”


预期输出:“g、od、yzal、eht、revo、spmuj、xof nw、orb kc、iuq eh、T”

这是您可以使用的代码

String original =  "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g";

    String reverse = original.replaceAll(",","");
    StringBuilder rev = new StringBuilder(reverse);
    rev = rev.reverse();
    String output="";
    int j = 0;
    for (int i = 0; i < original.length(); i++) {
        if(original.charAt(i) == ','){
            output += ",";
        }else{
            output+=rev.charAt(j++);
        }
    }

     System.out.println(output);
String original=“T,he,quick,bro,wn f,ox jump,s over,the l,azy do,g”;
字符串reverse=original.replaceAll(“,”和“”);
StringBuilder版本=新StringBuilder(反向);
rev=rev.reverse();
字符串输出=”;
int j=0;
对于(int i=0;i
这是您输入的代码

public class Test {
    public static void main(String [] args){
        String original =  "T,he ,quick, bro,wn f,ox jump,s over, the l,azy do,g";

         String reverse = "";
          int length = original.length();

          for ( int i = length - 1 ; i >= 0 ; i-- )
             reverse = reverse + original.charAt(i);

          System.out.println("Reverse of entered string is: "+reverse);
    }
}

使用
StringBuffer
Stack
在堆栈上保存逗号的位置反转插入逗号后,首先删除所有逗号并在堆栈上保存它们的索引。使用
stringBufferObject.deleteCharAt(索引)
用于删除字符并使用
stringBufferObject.reverse()用于反转字符串。

好的,到目前为止您尝试了什么?除了张贴在这里。可能的重复我把错误的重复:我能做的是扭转字符串,包括逗号,s。类Reverse{public static void main(String[]args){String phrase=“\”T,he,quick,bro,wn f,ox jump,s over,the l,azy do,g\”;phrase=new StringBuffer(phrase).Reverse().toString();System.out.println(“反向字符串:“+phrase”);}但我不知道如何使逗号保持在原来的位置。这是输出:g,od yza,l eht,revo s,pmuj xo,f nw,orb,kciuq,呃,预期的输出:“g,od,yzal,eht,revo,spmuj,xof nw,orb kc,iuq eh,t”我认为他想要的输出和输入不一样。输入和输出中逗号的索引应该是相同的。我编辑代码并修复它。谢谢亚历山大,那是错的。你应该再读一遍他的问题。+1个好答案——足够详细,让人能理解,但不是填鸭式的答案。我怀疑OP是在期待后者:-)