首页 > 解决方案 > 使用用户字符串中的反向单词创建数组

问题描述

我正在创建一个程序,用户在其中输入一串单词(例如:我爱你),程序返回字符串中的单词数组(例如:I evol ouy)。但是,我无法让我的代码正确编译,并尝试调试,但看不到问题出在哪里。

我试图在 Slack 上寻找类似的问题,但发现的问题与从字符串中重新排列单词有关(例如:你我爱),我找不到与我类似的问题,涉及将字符串转换为数组和然后操作数组。

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string to see it in reverse: ");
    String userEntry = sc.nextLine();
    char[] entryToChar = userEntry.toCharArray();
    System.out.println(Arrays.toString(entryToChar));
    String[] splitInput = userEntry.split(" "); 
    String reverseWord = "";
    int temp;
    String[] reverseString = new String[splitInput.length]; 

    for (int i = 0; i < splitInput.length; i++) 
    {
        String word = splitInput[i];            


        for (int j = word.length()-1; j >= 0; j--) 
        {
            reverseWord = reverseWord + word.charAt(j);
        }            

        for (int k = 0; k < splitInput.length; k++) {
                temp = splitInput[i];
                splitInput[i] = reverseWord[j];
                reverseWord[j] = temp;

                }

     }  System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);

我正在避免使用“StringBuilder”方法,因为我还没有研究过它,并尝试查看是否可以使用交换来获取新字符串,如下面的代码所示:

temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;

标签: javaarraysstring

解决方案


import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String word, reverseWord;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string to see it in reverse: ");
        String userEntry = sc.nextLine();

用户输入:我爱你

        String[] splitInput = userEntry.split(" ");

splitInput:[我,爱,你]

        for (int i = 0; i < splitInput.length; i++)
        {
            word = splitInput[i];
            reverseWord = "";
            for (int j = word.length()-1; j >= 0; j--)
            {
                reverseWord = reverseWord + word.charAt(j);
            }
            splitInput[i] = reverseWord;
        }

splitInput: [I, evol, uoy]

        System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
    }
}

你的单词倒着写的字符串是:I evol uoy


推荐阅读