用新字符移动字符串末尾的第一个单词



我有一个格式为word1**word2的单词列表

我想把第一个单词放在字符串的末尾,像word2 - word1

如何分割第一个没有**的单词并在粘贴单词之前添加-?

我想让行从文件words.txt中读取,并创建一个新文件new-words.txt

例如,我想将Bibi**Tina转换为Tina - Bibi

编辑:我尝试了一个新的代码。现在我在控制台上得到了正确的输出,但是新创建的文件是空的。

import java.io.*;
import java.util.*;
public class Main { 

public static void main(String args[]) {
List<String> lines = new ArrayList<String>();
String line = null;
try {
File f1 = new File("C:\Users\PC\Desktop\new-words.txt");
FileOutputStream fop = new FileOutputStream(f1);
FileReader fr = new FileReader(f1);
BufferedReader  br = new BufferedReader(new FileReader("C:\\Users\\PC\\Desktop\words.txt"));


while ((line = br.readLine()) != null) {
if (!line.contains("\*\*\yok")) {
String[] a = line.split("\*\*");
System.out.println(a[1] + "  - " + a[0]);
}
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

}

查看官方java文档。如何使用write方法有3种选择,它们都不接受字符串作为参数。

  • 空白写(byte [] b):从指定的字节数组中写入b.length字节
  • 空白写(byte [] b, int, int len):写从指定字节数组的偏移量开始到此的Len字节
  • void write(int b):将指定字节写入this

您需要将字符串转换为字节[],以便使用文件输出流将其写入文件。请参阅StackOverflow帖子,其中讨论了如何做到这一点。

这可能对您有用。使用接受正则表达式的replaceAll

  • (\w+)- capture a word
  • \*\*-背靠背星号(必须转义,因为它们有特殊的正则表达式属性)
  • $1$2-对刚刚捕获的单词的反向引用。
String s = "This is a test word1**word2";
s = s.replaceAll("(\w+)\*\*(\w+)", "$2 - $1");
System.out.println(s);

打印

This is a test word2 - word1

如果短语不匹配,将返回原始字符串。

所以在你的例子中应该是这样的:

while ((line = br.readLine()) != null) {
line = line.replaceAll("(\w+)\*\*(\w+)", "$2 - $1");
System.out.println(line);
}
star.split('**').reverse().join('-')