【问题标题】:Is there any way to extract only single character words from a String?有没有办法从字符串中只提取单个字符的单词?
【发布时间】:2014-11-26 11:05:06
【问题描述】:

给定一个字符串,例如“Hello a World b”,有什么方法可以打印出字符“a”和“b”而忽略“Hello”和“World”?

我只想打印出单字母单词而忽略多字母字符串。

【问题讨论】:

    标签: java string char extract


    【解决方案1】:

    使用正确的正则表达式...

    Matcher m = Pattern.compile("\\b[a-zA-Z]\\b").matcher(str);
    while (m.find())
        System.out.println(m.group());
    

    相同的结果,但代码更少,是删除所有多字母单词然后在空格上分割:

    for (String letter : str.replaceAll("\\w\\w+", "").trim().split(" +"))
        System.out.println(letter);
    

    【讨论】:

    • 对其进行了测试,并让它完全按照我想要的方式工作。非常感谢!你是救生员!
    【解决方案2】:

    当然,你需要使用 String 类中的contains 方法

    List <String> emoticons = new ArrayList();
    
    for(String emoticon : emoticons) {
           String input = "Hello :) World :P";
           boolean output= input.contains(emoticon);
           System.out.println("this emoticon "+emoticon+ is pressent);
    }
    

    希望对你有帮助:)

    【讨论】:

      【解决方案3】:

      您需要表情符号的映射以及应该替换它的字符。然后遍历地图,用字符(值)和你的集合替换表情(键)。

      有点像这样

      Map<String, String> emoticons = new HashMap<String, String>();
      //fill it with emoticons and what string should replace it
      
      String s = "Hello :) World :P";
      
      for(Map.Entry<String, String> entry: emoticons.entrySet()){
          s = s.replace(entry.getKey(), entry.getValue());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 2016-12-27
        • 1970-01-01
        • 2022-10-19
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多