java - 如何反转数组中的字符串?

标签 java recursion

import java.io.*;
import java.util.Scanner;

class FileReverse{
   public static void main(String[] args) throws IOException{

      //charAt(int index): Returns the char value at the specified index.
      //substring(int beginindex, int endindex): Returns a new string that is a substring of the string. 
      //valueOf(char c): Returns the string representation of the char argument

      Scanner in = null;
      PrintWriter out = null;
      String line = null;
      String[] token = null;
      int i ,n ;

      // check number of command line arguments is at least 2
      if(args.length < 2){
         System.out.println("Usage: FileCopy <input file> <output file>");
         System.exit(1);
      }

      // open files
      in = new Scanner(new File(args[0]));
      out = new PrintWriter(new FileWriter(args[1]));

      // read lines from in, extract and print tokens from each line
      while( in.hasNextLine() ){
         // trim leading and trailing spaces, then add one trailing space so 
         // split works on blank lines
         line = in.nextLine().trim() + " "; 

         // split line around white space 
         token = line.split("\\s+"); 

         // reverses the input and prints it to the console.
         n = token.length;
         for(i=0; i<n; i++){
            stringReverse(token[i],(n-1));
            System.out.println(token);
         } 
      }

      // close files
      in.close();
      out.close();
   }

   public static String stringReverse(String s, int n){
      if(n == 0){
         return s.charAt(0) + "";
      }

      char let = s.charAt(n);
      return let + stringReverse(s,(n-1));
   }
}

我们得到一个包含此输入的文件

abc 定义 你好

jkl mnop q
rstu v wxyz

并且它必须返回为

中国篮球协会
GFED

lkj
庞姆
q
乌兹别克斯坦
v

我的代码可以编译,但我不断收到indexoutofboundsException,但我无法解决这个问题。非常感谢您的帮助!

最佳答案

您将在每个空格处拆分字符串。在下面的代码中

n = token.length;
for(i=0; i<n; i++){
    stringReverse(token[i],(n-1));
    System.out.println(token);
}

您检查有多少个元素由空格分隔。但您犯的错误是,您将 n-1 解析为函数 Stringreverse (除了您不存储返回值的事实之外)。您正在使用第二个参数作为 Stringlength,但您当前正在做的是, 您传递的是用空格分割初始 String 后返回的数组元素的数量。您应该将其称为:

for(i=0; i<n; i++){
    String reversed = stringReverse(token[i],token[i].length()-1);
    System.out.println(reversed);
} 

关于java - 如何反转数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36589552/

相关文章:

java - MongoDB Java 驱动程序 : query where d>2, a ="ABC",b ="AA"

java - jvm字符串池intern中有多少个字符串

java - 将对象类型转换为枚举不会给出枚举或错误

list - 如何使用递归删除 Racket 列表中的第一个和最后一个元素

algorithm - 分而治之、分支和归约有什么区别?

python - BeautifulSoup 和 python 。无法通过递归获取所有节点,因为出现 "maximum recursion depth exceeded while calling a Python object"错误

java - 检查文件是否存在于特定目录中

java - Jena 库未将输出写入外部 RDF/XML 文件

java - 二叉搜索树小计数练习

recursion - 如何将递归函数的值返回到数组