【问题标题】:split words from text using java [closed]使用java从文本中拆分单词[关闭]
【发布时间】:2013-12-29 23:33:28
【问题描述】:

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

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

【问题讨论】:

  • 您已经尝试过自己解决什么问题?
  • 欢迎来到 SO!请阅读About 页面:“不要问...您尚未尝试找到答案的问题(展示您的工作!)”。
  • 从阅读String JavaDocs 开始,然后尝试搜索 SO 以获取更多示例...

标签: java text split


【解决方案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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2022-08-16
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 2019-07-24
    相关资源
    最近更新 更多