A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

1黑马币
本人菜鸟一枚,求大神解答。

最佳答案

查看完整内容

获取空格数出现的次数+1,当然我指的是标点符号后也有空格。 如果不这么做的话也可以,不过就是麻烦了点,就是也要判断获取各种标点符号在文章中出现的次数。然后在前面获得的(空格数+标点符号出现的次数)总和。注意,不要获取单双引号。 具体实现思路就是: 1.定义个计数器 2.获取kk第一次出现的位置 3.从第一次出现低位之后剩余的字符串中继续获取kk出现的位置。 每获取一次就计数一次 4.当获取不到时,计数完成 代码还是 ...

9 个回复

倒序浏览
获取空格数出现的次数+1,当然我指的是标点符号后也有空格。
如果不这么做的话也可以,不过就是麻烦了点,就是也要判断获取各种标点符号在文章中出现的次数。然后在前面获得的(空格数+标点符号出现的次数)总和。注意,不要获取单双引号。
具体实现思路就是:
1.定义个计数器
2.获取kk第一次出现的位置
3.从第一次出现低位之后剩余的字符串中继续获取kk出现的位置。
    每获取一次就计数一次
4.当获取不到时,计数完成
代码还是希望LZ能够自己实现,我相信你能行的!加油!
回复 使用道具 举报

  1. public class Demo6 {

  2.         public static void main(String[] args) {
  3.                 // TODO Auto-generated method stub
  4.                 String str="abcdefgh";
  5.                 String temp = str.concat("a");//concat(String str) 将指定字符串联到此字符串的结尾。
  6.                 System.out.println(temp);
  7.                 int length = temp.lastIndexOf("a");//lastIndexOf(int ch) 返回最后一次出现的指定字符在此字符串中的索引
  8.                 System.out.println(length);//最后一个的下标就是原数组的长度
  9.                
  10.         }

  11. }
复制代码
回复 使用道具 举报
  1. public class Demo6 {

  2.         public static void main(String[] args) {
  3.                 // TODO Auto-generated method stub
  4.                 int num = 0;
  5.                 String str = "We are the world! We are the children.";
  6.                 String temp = str.replaceAll(" ", "  ");

  7.                 num = temp.length() - str.length() + 1;
  8.                 System.out.println(num);
  9.         }

  10. }
复制代码
回复 使用道具 举报
自己思考一下吧。。。。
回复 使用道具 举报
import java.util.regex.*;

class CountWords{
       
        public static void main(String[] args){
                String str="This is a dog";
                String regex="\\b\\w+\\b";
                System.out.println(count(regex,str));
               
        }

                public static int count(String regex,String str){
                        int sum=0;
                        Pattern p=Pattern.compile(regex);
                        Matcher m=p.matcher(str);
                        while(m.find()){
                                sum++;
                        }
                        return sum;
                }
}

回复 使用道具 举报
直接用String 里面的split方法分割,返回一个String数组,统计数组长度。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马