简体   繁体   English

使用用户字符串中的反向单词创建数组

[英]Create array with reversed words from user string

I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). 我正在创建一个程序,其中用户输入一串单词(例如:我爱你),并且该程序返回字符串中的单词数组,这些单词的单词是向后拼写的(例如:evol ouy)。 However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is. 但是,我无法正确编译我的代码,并尝试调试,但是看不到问题出在哪里。

I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array. 我试图在Slack上寻找类似的问题,但是发现问题与从字符串重新排列单词有关(例如:我爱你),但我找不到与我类似的问题,涉及将字符串转换为Array和然后操作数组。

    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]);

I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below: 我正在避免使用“ StringBuilder”方法,因为我尚未对其进行研究,而是尝试查看是否可以通过交换来获取新字符串,如以下代码所示:

temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
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();

userEntry: I love you userEntry:我爱你

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

splitInput: [I, love, you] 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] splitInput:[I,evol,uoy]

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

Your string with words spelled backwards is: I evol uoy 您的带有反义词的字符串是:我进化

Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String. 您的代码没有得到编译,因为splitInput[i]为String时, tmp变量声明为int。

The other problem is variable j is outside its block scope from where you are trying to access. 另一个问题是变量j在尝试访问的块范围之外。

Make your logic clear before writing code to achieve correct result. 在编写代码之前要弄清楚逻辑,以获得正确的结果。

A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. 一个好的Java程序员应该知道语言中存在哪些工具,并在她/他的设计中适当地使用它们。 I would suggest to use the class StringBuilder , which has a method for reversing the string. 我建议使用StringBuilder类,该类具有用于反转字符串的方法。 Your program could look like this: 您的程序可能如下所示:

while in.hasNext() {
  StringBuilder sb = in.next();
  sb.reverse();
  System.out.println(sb.toString());
}

If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse() . 如果您想亲自编写反向函数进行练习,则可以简单地定义一个采用字符串并返回反向字符串的方法,然后调用该方法代替sb.reverse()

Please know that String in Java is an immutable object. 请注意,Java中的String是不可变的对象。 You cannot modify it directly. 您不能直接修改它。 You can have modified copies returned. 您可以返回修改后的副本。
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above. 另一方面,如您在上面的代码中看到的, StringBuilder允许程序员直接修改对象。

You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice. 您需要将原始字符串拆分为一个数组,然后将每个字符串反转并插入到新数组中,在这里您可以使用StringBuilder作为一种好习惯。

class Testarray{
    public static void main(String args[]){
        String str = "I am Engineer";
        String[] spArray = str.split(" ");
        String farr[] = new String[spArray.length];

        for(int i=0;i<spArray.length;i++){
            String split = spArray[i];
            farr[i]=reverseString(split);
        }

        for(int i=0;i<farr.length;i++){
            System.out.println(farr[i]);
        }
    }
    public static String reverseString(String str){  
        char ch[]=str.toCharArray();  
        String rev="";  
        for(int i=ch.length-1;i>=0;i--){  
            rev+=ch[i];  
        }  
        return rev;  
    }  
}

There are a few things going on here, and I think in some places you're mixing up between strings and arrays. 这里发生了一些事情,我认为在某些地方,您在字符串和数组之间混在一起。

Let's try to break this problem down into smaller problems. 让我们尝试将此问题分解为较小的问题。

First, we need to reverse a single word. 首先,我们需要反转一个单词。 Your first inner loop (the one that uses j ) does that, so let's extract it into its own method: 您的第一个内部循环(使用j循环)做到了,所以让我们将其提取到自己的方法中:

public static String reverseWord(String word) {
    String reverseWord = "";
    for (int j = word.length()-1; j >= 0; j--) {
        reverseWord = reverseWord + word.charAt(j);
    }
    return reverseWord;
}

Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable): 虽然,您应该注意,在循环中串接这样的字符串并不能提高性能,并且使用StringBuilder可能会更快(尽管对于如此小的应用程序,它可能不会引起注意):

public static String reverseWord(String word) {
    StringBuilder reverseWord = new StringBuilder(word.length());
    for (int j = word.length()-1; j >= 0; j--) {
        reverseWord = reverseWord.append(word.charAt(j));
    }
    return reverseWord.toString();
}

Once you have that, you can split the input string (like you did), revere each word, and join them back together: 一旦有了它,就可以拆分输入字符串(就像以前一样),欣赏每个单词,然后将它们重新组合在一起:

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(" ");

for (int i = 0; i < splitInput.length; i++) {
    splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " + 
                   String.join(" ", splitInput));

All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse: 您需要做的就是将原始句子拆分成单独的单词,然后使用StringBuilder.reverse()来获取相反的单词:

public static void main(String... args) {
    String str = getSentenceFromConsole();
    System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}

private static String getSentenceFromConsole() {
    try (Scanner scan = new Scanner(System.in)) {
        System.out.print("Enter a string to see it in reverse: ");
        return scan.nextLine();
    }
}

private static String reversLettersInWords(String str) {
    return Arrays.stream(str.split("\\s+"))
                 .map(word -> new StringBuilder(word).reverse().toString())
                 .collect(Collectors.joining(" "));
}

i try with your code 我尝试使用您的代码

    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(" "); 
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < splitInput.length; i++) {
        String word = splitInput[i];
        for (int j = word.length() - 1; j >= 0; j--) {
            sb.append(word.charAt(j));
        }
        sb.append(" ");
    }
    System.out.println("Your sttring with words spelled backwards is " + sb.toString());

here i remove all access line of code.... 在这里,我删除所有的代码访问行。

String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);

You can use this implementation to try to reverse the string elements in the array. 您可以使用此实现来尝试反转数组中的字符串元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM