Java - 反转字符串中的单词

发布于 2024-12-12 01:23:54 字数 853 浏览 0 评论 0原文

这是我们的代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class reverse {

public static void main(String[] args) throws FileNotFoundException {
    File fil = new File("textFile.txt");
    Scanner scan = new Scanner(fil);

    while (scan.hasNext()) {
        String in = scan.nextLine();
        in = new StringBuffer(in).reverse().toString();
        Pattern replace = Pattern.compile("\\W+");
        Matcher matcher = replace.matcher(in);
        System.out.println(matcher.replaceAll("\t"));
        }



    }

}

在我们的 textFile.txt 中,我们在不同的行中有字母、数字和单词。我们想以相反的顺序打印它们。因此,如果一行是:是的,4 巧克力牛奶。我们要打印出:牛奶巧克力 4 是的。

我们的代码以相反的方式打印出单词,所以 yes 变成了 sey。我们不希望这样,但又不知道如何改变。我们一直在考虑创建一个堆栈,但我们不知道它如何在没有模式和匹配器的情况下一起工作。

This is our code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class reverse {

public static void main(String[] args) throws FileNotFoundException {
    File fil = new File("textFile.txt");
    Scanner scan = new Scanner(fil);

    while (scan.hasNext()) {
        String in = scan.nextLine();
        in = new StringBuffer(in).reverse().toString();
        Pattern replace = Pattern.compile("\\W+");
        Matcher matcher = replace.matcher(in);
        System.out.println(matcher.replaceAll("\t"));
        }



    }

}

In our textFile.txt we have letters, numbers and words in different lines. We want print them out in reverse order. So if one line is: Yes, 4 Chocolate milk. We want to print out: milk Chocolate 4 Yes.

Our code prints out words in reverse, so yes becomes sey. We don't want it to be like this, but don't know how to change it. We've been thinking about creating a stack, but we don't how it'll work together with out Pattern and Matcher stuff.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

_失温 2024-12-19 01:23:54

您不应该反转您读取的行,而应该将该行拆分为一个集合并反转它。
您所做的就是反转字符,因此您会得到以下结果:

Yes, 4 Chocolate milk -> klim etalocohC 4 , seY

如果将行拆分为 ["Yes","4","Chocolate milk"] 您可以反转该数组/列表。

问题是:我猜你想保持巧克力牛奶的顺序,所以你需要定义哪些单词属于一起。如果您的输入始终为 ,; 您可以首先在 , 上拆分,以分隔第一个 ,然后在其余部分的第一个空格上拆分数字和第二个

更新:试试这个:

String input = "Yes sir, 4 Chocolate milk";

//Pattern is: 
//- one or more words separated by whitespace as group 1: ((?:\\w+\\s*)+)
//- a comma 
//- optional whitespace: \\s*
//- an integer number as group 2: (\\d+)
//- optional whitespace \\s*
//- an arbitrary rest (which might contain anything) as group 3: (.*)
Pattern p = Pattern.compile( "((?:\\w+\\s*)+),\\s*(\\d+)\\s*(.*)" );
Matcher m = p.matcher( input );

List<String> list = new ArrayList<String>();
while(m.find()) {
  list.add( m.group( 1 ) );
  list.add( m.group( 2 ) );
  list.add( m.group( 3 ) );
}

Collections.reverse( list );
for( String s : list) {
  System.out.println(s);
}

输出应该是

Chocolate milk
4
Yes sir

请注意,这取决于您输入的布局,并且只是为了提供一个开始。您还需要将其与其他模式匹配逻辑集成。

You shouldn't reverse the line you read but split the line into a collection and reverse that.
What you do is reversing the characters, so you get this:

Yes, 4 Chocolate milk -> klim etalocohC 4 , seY

If you split the line into ["Yes","4","Chocolate milk"] you can reverse that array/list.

The problem is: I guess you want to keep Chocolate milk in that order, so you'd need to define what words belong together. If your input is always <words>, <number> <words> you could split on , first, to separate the first <words> and then on the first whitespace of the remainder in order to split the number and the second <words>.

Update: try this:

String input = "Yes sir, 4 Chocolate milk";

//Pattern is: 
//- one or more words separated by whitespace as group 1: ((?:\\w+\\s*)+)
//- a comma 
//- optional whitespace: \\s*
//- an integer number as group 2: (\\d+)
//- optional whitespace \\s*
//- an arbitrary rest (which might contain anything) as group 3: (.*)
Pattern p = Pattern.compile( "((?:\\w+\\s*)+),\\s*(\\d+)\\s*(.*)" );
Matcher m = p.matcher( input );

List<String> list = new ArrayList<String>();
while(m.find()) {
  list.add( m.group( 1 ) );
  list.add( m.group( 2 ) );
  list.add( m.group( 3 ) );
}

Collections.reverse( list );
for( String s : list) {
  System.out.println(s);
}

The output should be

Chocolate milk
4
Yes sir

Note that this depends on the layout of your input and is just meant to provide a start. You'd also need to integrate that with your other pattern matching logic.

待"谢繁草 2024-12-19 01:23:54

尝试使用 Scanner 或简单的 String.split() 来创建行中所有标记的数组或集合。然后只需使用 for 循环向后迭代即可重新创建该行。您还可以使用Collections.reverse() 来实现此目的。

Try using Scanner or simply String.split() to create an Array or Collection of all tokens within your line. Then just use a for-loop to iterate over it backwards to recreate the line. You also could use Collections.reverse() to achieve this.

终难遇 2024-12-19 01:23:54

按单词拆分字符串,将结果保存到字符串数组中,然后从最后一个元素到第一个元素显示字符串。
代码:

public static void main(String[] args) {
    String hello = "bananas 45 guns me likes 3";
    String[] reverse_me = hello.split(" ");

    // the -1 is because the index starts in zero :-0)
    for(int i = reverse_me.length-1; i >= 0 ; i--){
        System.out.println(reverse_me[i]);
    }

}

输出:

3
likes
me
guns
45
bananas

Split the string by words, save result into an array of strings and then display the string from last to first element.
Code:

public static void main(String[] args) {
    String hello = "bananas 45 guns me likes 3";
    String[] reverse_me = hello.split(" ");

    // the -1 is because the index starts in zero :-0)
    for(int i = reverse_me.length-1; i >= 0 ; i--){
        System.out.println(reverse_me[i]);
    }

}

Output:

3
likes
me
guns
45
bananas
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文