疯狂java讲义第七章课后第3题答案

3.将A1B2C3D4E5F6G7H8拆分开来,并分别存入int[]和String[]数组。得到的结果为[1,2,3,4,5,6,7,8]和[A,B,C,D,E,F,G,H]。

import java.util.*;
import java.util.regex.*;
import java.io.*;
public class Test
{

	public static void main(String[] args) throws Exception
	{
		//存储用的数组
		int[] nums = new int[8];
		String[] strs = new String[8];
		//记录位置
		int n = 0;
		int s = 0;
		//开始解析文本
		String str = "A1B2C3D4E5F6G7H8";
		Pattern p1 = Pattern.compile("\\d");//匹配数字
		Matcher m1 = p1.matcher(str);
		while(m1.find())
		{
			nums[n++] = Integer.parseInt(m1.group());
		}
		System.out.println(Arrays.toString(nums));

		p1 = Pattern.compile("\\D"); //匹配字母
		m1 = p1.matcher(str);
		while(m1.find())
		{
			strs[s++] = m1.group();
		}
		System.out.println(Arrays.toString(strs));
		
	}
}

2021年12月24日
以下才是正解,上面的方法是复杂化了,只需要使用String的split()方法结合正则表达式即可

public class Test
{
	public static void main(String[] args)
	{
		String str = "A1B2C3D4E5F6G7H8";
		String[] nums = str.split("\\D");
		int[] nums2 = new int[nums.length-1];
		for(int i = 1 ; i < nums.length; i++)
		{
			
			nums2[i-1] = Integer.valueOf(nums[i]);
		}
		System.out.println(Arrays.toString(nums2));
		String[] words = str.split("\\d");
		System.out.println(Arrays.toString(words));
	}
}

2021年12月25日
下面的解法也比第一种要好得多

import java.util.*;
import java.util.regex.*;
public class Test
{
	public static void main(String[] args)
	{
		String str = "a1b2c3d4e5";
		p = Pattern.compile("\\d");
		System.out.println(Arrays.toString(p.split(str)));
		p = Pattern.compile("\\D");
		System.out.println(Arrays.toString(p.split(str)));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

细水长流cpu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值