【问题标题】:Given a string remove all the special characters except hyphen and count number of words给定一个字符串,删除除连字符以外的所有特殊字符并计算单词数
【发布时间】:2021-03-09 01:26:07
【问题描述】:

给定一个字符串“这是高科技的就业市场吗?我们在哪里。职业” 我必须删除除连字符外的所有特殊字符并计算字符串中的单词数,因此在这种情况下输出应为 10。 我写了下面的程序,但它没有通过测试用例。

public int countWords(String str) {
    if(str.isEmpty() || str==null)
       return 0;
    String replacedString = str.replaceAll(["^a-zA-Z0-9- ]","");
    String[] arrWords = replacedString.split("\\s+");
    return arrWords.length;
}

【问题讨论】:

  • 你能发布你的单元测试吗?
  • 这是在线编译器问题,我无法确切看到哪个测试用例失败

标签: java arrays string


【解决方案1】:

您可以使用正则表达式[\p{Punct}&&[^-]],其中\p{Punct} 代表标点符号。如果要替换除字母、数字、连字符和空格以外的所有内容,可以使用正则表达式 [^\p{Alnum}\s-],其中 \p{Alnum} 代表 alphanumeric character

演示:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String str = "this is high-tech job market in which? we make. careers";

        String[] arr = str.replaceAll("[\\p{Punct}&&[^-]]", "").split("\\s+");

        System.out.println(Arrays.toString(arr));

        int count = arr.length;

        System.out.println(count);
    }
}

输出:

[this, is, high-tech, job, market, in, which, we, make, careers]
10

【讨论】:

    【解决方案2】:

    首先,空/空条件应该是相反的顺序:

        if(str==null || str.isEmpty())
    

    你明白为什么吗? (提示:Java 评估是惰性的)

    另外,是否应该删除“-”(减号)?

    【讨论】:

    • [^] 是正则表达式的否定,所以正则表达式的意思是“替换所有除了”
    • 我知道什么是正则表达式:) 你可以看看作者的定义“删除所有特殊字符”。所以我问“-”是否算特殊字符?他将其用作例外(即 - 它不是特殊字符,本例中的值为 10),所以我想验证一下。
    • 哦,问题正文中缺少“连字符”,但在标题中。对不起。
    【解决方案3】:

    您可以执行此操作来计算代码中的 10 个单词。 如果它是非单词 (\W),则替换您的字符串,并为连字符设置例外。

    public class Test {
    
        public static void main(String[] args) {
            String myString = "this is high-tech job market in which? we make. careers";
            myString = myString.replaceAll("[\\W&&[^\\-]]", " ");
            String[] arrWords = myString.split("\\s+");
            System.out.println(arrWords.length);
        }
    
    }
    

    使用\W 的好处是它包含了所有的unicode 标点符号。

    例如,如果您有这些字符‘ „\p{Punct} 将不起作用。

    如果您需要,这里是使用Pattern.UNICODE_CHARACTER_CLASS 的替代方法:

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.regex.Pattern;
    
    public class Test {
    
        public static void main(String[] args) {
            String myString = "this is high-tech job market ‘ „ in which? we make. careers";
            String[] arrWords2 = Pattern.compile("[\\p{Punct}&&[^-]]|\\s", Pattern.UNICODE_CHARACTER_CLASS).split(myString);
            List<String> arrayList = new ArrayList<String>(Arrays.asList(arrWords2));
            arrayList.removeAll(Arrays.asList("",null));
            System.out.println(arrayList);
            System.out.println(arrayList.size());
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      相关资源
      最近更新 更多