统计任意一个字符串中,英文单词的总数,最长的单词长度,最短的单词长度,单词的平均长度(用JAVA写哦)例如:“ab+12

1个回答

  • 首先,你的例子string中最长的是dfg,长度是3,不是4,平均也是2.2

    然后是代码

    final String regex = "[^a-zA-Z]+";

    String s = "ab+12cd*123dfg%&()as23BG";

    String[] words = s.split(regex);

    int min = Integer.MAX_VALUE,max = 0,total = 0,length;

    for (String word :words) {

    length = word.length();

    total += length;

    min = Math.min(min,length);

    max = Math.max(max,length);

    }

    System.out.printf("Shortest length:%dn",min);

    System.out.printf("Longest length:%dn",max);

    System.out.printf("Average length:%fn",((double) total) / words.length);