简单点

weixin_45844740 2019-12-05 09:19:10
求大佬教我
...全文
50 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
abcdefg* 2019-12-05
  • 打赏
  • 举报
回复

System.out.println("请输入:");
		Scanner scanner=new Scanner(System.in);
		String next = scanner.next();
		System.out.println(next);
		long s=System.currentTimeMillis();
		next=next+"$";
		String temp="";
		int count=0;
		for(int i=0;i<next.length()-1;i++) {
			temp=""+next.charAt(i)+next.charAt(i+1);
			if("ab".equals(temp)) {
				count++;
				i++;
			}
		}
		System.out.println("共有"+count+"个ab,花费"+(System.currentTimeMillis()-s));
程序yang 2019-12-05
  • 打赏
  • 举报
回复
统计其中有多少个“ab”子字符串?“ab”需要连在一起才算一个吧?
qybao 2019-12-05
  • 打赏
  • 举报
回复
引用 2 楼 qybao 的回复:
System.out.printf("1. 一共有ab子字串:%d\n", s.split(reg).length); //改一下,这样更简单

用数组分割的话,数组长度要减1

int len = s.split(reg).length;
System.out.printf("1. 一共有ab子字串:%d\n", (len > 0 ? len-1 : len));
qybao 2019-12-05
  • 打赏
  • 举报
回复
System.out.printf("1. 一共有ab子字串:%d\n", s.split(reg).length); //改一下,这样更简单
qybao 2019-12-05
  • 打赏
  • 举报
回复
for example

import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
try {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String reg = "ab";
System.out.printf("1. 一共有ab子字串:%d\n", (s.length()- s.replaceAll(reg, "").length())/reg.length());
System.out.printf("2. 把ab替换为xy后:%s\n", s.replaceAll(reg, "xy"));

} catch (Exception e) {
e.printStackTrace();
}
}
}

58,452

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧