代码之家  ›  专栏  ›  技术社区  ›  Karthikeyan

Java-识别最后一个[关闭]有特殊字符的字符串

  •  -1
  • Karthikeyan  · 技术社区  · 6 年前

    在迭代am时有一个字符串列表,试图识别包含任何特殊字符的字符串的最后一个字符。

    例如:

    Apple,
    Apple
    Apple(
    Apples.
    Apples
    

    预期结果:

    Apple
    Apples
    

    请在下面找到我的代码,从现在起将特殊字符替换为“”(空),但我想删除字符串本身。

    for (TermSuggestion.Entry entry : termSuggestion.getEntries()) { 
        for (TermSuggestion.Entry.Option option : entry) { 
            String suggestText = option.getText().string();
            String result = suggestText.replaceAll("[-+.^:,]()","");
            System.out.println("Print String--->  "+result);
        }
    }
    
    4 回复  |  直到 5 年前
        1
  •  1
  •   Michael    6 年前

    你可以用 Character.isAlphabetic 找出它是否是一个特殊的字符。你可以用 String.charAt 得到最后一个角色。

    for (TermSuggestion.Entry entry : termSuggestion.getEntries())
    { 
        for (TermSuggestion.Entry.Option option : entry)
        { 
            String suggestText = option.getText().string();
            if (Character.isAlphabetic(suggestText.charAt(suggestText.length()))
            {
                System.out.println("Print String--->  "+result);
            }
        }
    }
    
        2
  •  0
  •   Yogesh_D    6 年前

    你可以用这个正则表达式 .*[a-z]$ 只过滤以小写/小写字符结尾的单词。

        3
  •  0
  •   memo    6 年前

    去除 字符串,首先您的集合必须是可修改的。对你来说是 termSuggestion ,因此请确保是,否则请复制。 然后,使用 Iterator 通过调用 hasNext() next() . 一旦碰到要删除的字符串,请调用 remove() 方法。请参阅迭代器文档: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

        4
  •  0
  •   Fabien MIFSUD    6 年前

    下面是Streams和apache.commons.lang3的代码。

    List<String> strings = Arrays.asList("Apple", "Apple", "Apple", "Apples.", "Apples");
    String[] alphabet = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    List<String> result = strings.stream().filter(item -> StringUtils.endsWithAny(item, alphabet)).distinct().collect(Collectors.toList());