使用java从文本中分割单词

时间:2013-12-29 23:33:28

标签: java text split

我想在java上拆分这两列,并将法语单词放在arraylist中,将英语单词放在另一个arraylist中,谢谢你的帮助

bonjour;goodmorning
bonsoir;goodevening
chat;cat
comment;how
pourquoi;why

1 个答案:

答案 0 :(得分:1)

尝试这样的事情

private static final String safeTrim(String in) {
  if (in == null) {
    return "";
  }
  return in.trim();
}

public static void main(String[] args) {
  String in = "bonjour;goodmorning bonsoir;goodevening"
      + " chat;cat comment;how pourquoi;why";
  java.util.List<String> frenchList = new java.util.ArrayList<String>();
  java.util.List<String> englishList = new java.util.ArrayList<String>();
  String[] pairs = in.split(" ");
  // Split the input into pairs.
  for (String p : pairs) {
    // Split the pairs into words.
    String[] words = p.split(";");
    // Check that there are two words.
    if (words != null && words.length == 2) {
      if (safeTrim(words[0]).length() > 0
          && safeTrim(words[1]).length() > 0) {
        frenchList.add(words[0].trim());
        englishList.add(words[1].trim());
      }
    }
  }
  // Display the results.
  for (int i = 0; i < frenchList.size(); i++) {
    System.out.printf(
        "\"%s\" is \"%s\" en Français!\n",
        englishList.get(i), frenchList.get(i));
  }
}

当我运行它时,输出 -

"goodmorning" is "bonjour" en Français!
"goodevening" is "bonsoir" en Français!
"cat" is "chat" en Français!
"how" is "comment" en Français!
"why" is "pourquoi" en Français!