有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用字符串Java中的全名替换所有特殊字符的最佳方法是什么?

我想将字符串中的所有特殊字符转换为它们的全名

示例:

输入:什么是堆栈溢出

输出:什么是堆栈溢出问号

我用replaceall()来做,但是有没有更简单的方法来做,因为我必须为每个特殊字符写一行

text = text.replaceAll("\\.", " Fullstop ");
text = text.replaceAll("!", " Exclamation mark ");
text = text.replaceAll("\"", " Double quote ");
text = text.replaceAll("#", " Hashtag ");
...

共 (5) 个答案

  1. # 1 楼答案

    你可以用一句话来表达

    您可以链接字符串操作,即一个字符串操作的结果可以通过链接传递给下一个操作,如下所示:

    public class Main {
        public static void main(String[] args) {
            String text = "He asked, \"What is Stackoverflow?\"\nHow beautiful!\nNeither am I the God nor am I the Devil.";
            
            text = text.replaceAll("\\.", " Fullstop ")
                    .replaceAll("!", " Exclamation mark ")
                    .replaceAll("\"", " Double quote ")
                    .replaceAll("#", " Hashtag ");
            
            System.out.println(text);
        }
    }
    

    输出:

    He asked,  Double quote What is Stackoverflow? Double quote 
    How beautiful Exclamation mark 
    Neither am I the God nor am I the Devil Fullstop 
    
  2. # 2 楼答案

    使用IntStream可以一次完成

    String text= "Input: What is stack overflow?";
    System.out.println(
        text.codePoints().mapToObj( c -> {
          switch( c ) {
          case '.':
            return "‹Fullstop›";
          case '!':
            return "‹Exclamation mark›";
          case '"':
            return "‹Double quote›";
          case '#':
            return "‹Hashtag›";
          case '?':
            return "‹Question mark›";
          default:
            return String.valueOf( (char)c );
          }
        } ).collect( StringWriter::new, StringWriter::write,
            ( w1, w2 ) -> w1.write( w2.toString() ) ).toString() );
    

    …或根据Joop Eggen的想法改编(但保留原文)

    System.out.println(
        text.codePoints().collect( StringWriter::new,
            (w, c) -> w.write( Character.isAlphabetic( c )
                ? Character.toString( c ) : '‹' + Character.getName( c ) + '›'),
            ( w1, w2 ) -> w1.write( w2.toString() ) ).toString() );
    

    获取:Input‹COLON›‹SPACE›What‹SPACE›is‹SPACE›stack‹SPACE›overflow‹QUESTION MARK›

  3. # 3 楼答案

    这里的一种方法是维护一个包含所有符号及其名称替换的hashmap。然后,对输入字符串执行正则表达式迭代并进行所有替换

    Map<String, String> terms = new HashMap<>();
    terms.put(".", " Fullstop ");
    terms.put("!", " Exclamation mark ");
    terms.put("\"", " Double quote ");
    terms.put("#", " Hashtag ");
    
    String input = "The quick! brown #fox \"jumps\" over the lazy dog.";
    Pattern pattern = Pattern.compile("[.!\"#]");
    Matcher matcher = pattern.matcher(input);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(buffer, terms.get(matcher.group(0)));
    }
    matcher.appendTail(buffer);
    
    System.out.println("input:  " + input);
    System.out.println("output: " + buffer.toString());
    

    这张照片是:

    input:  The quick! brown #fox "jumps" over the lazy dog.
    output: The quick Exclamation mark  brown  Hashtag fox  Double quote jumps Double quote  over the lazy dog Fullstop 
    

    上面的方法看起来有点冗长,但实际上所有的核心替换逻辑都发生在一行while循环中。如果您使用的是Java8,那么也可以使用Matcher流方法,但逻辑基本相同

  4. # 4 楼答案

    您可以使用Stream

    String text= "Input: What is stack overflow?";
    HashMap<String, String> map = new HashMap<String, String>(){{
        put("\\.", " Fullstop ");
        put("!", " Exclamation mark ");
        put("\"", " Double quote ");
        put("#", " Hashtag ");
        put("?", " question mark");
    }};
    System.out.println(
            Stream.of(text.split(""))
                    .map(s -> map.getOrDefault(s,s))
                    .collect(Collectors.joining())
    );
    
  5. # 5 楼答案

    查看内置的Unicode名称:

        String s = "a!\".";
        s.codePoints()
                .filter(cp -> !Character.isAlphabetic(cp))
                .forEach(cp -> System.out.println(Character.getName(cp)));
    
    EXCLAMATION MARK
    QUOTATION MARK
    FULL STOP
    

    使用toLowerCase/大写,您可以获得一个完整的&;紧凑的结果