黑马程序员技术交流社区
标题:
周末答题之我的答案
[打印本页]
作者:
adalvik
时间:
2015-4-12 23:46
标题:
周末答题之我的答案
下面是题目
题目一:写一个正则表达式,可以匹配手机号。规则: 第1位是1,第二位可以是数字3458其中之一,后面4位任意数字,最后5位为任意相同的数字。例如:18601088888、13912366666
题目二:编写程序,打印1到100之内的整数,但数字中包含7的要跳过,例如:17、27、71、72
题目三:编写程序,从一个字符串中按字节数截取一部分,但不能截取出半个中文,例如:从“hello枷哇”中截取2个字节是“he,截取6个字节也要是"hello",而不要出现半个中文。
下面是代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class main {
public static void main(String[] args) {
String number = "de1314875111111111";
System.out.println("题目1开始");
System.out.println(matcherPhone(number));
System.out.println("题目1结束\n");
System.out.println("题目2开始");
showNum();
System.out.println("题目2结束\n");
String a = "11我是世界";
System.out.println("题目3开始");
System.out.println(substring(a, 3));
System.out.println("题目3结束");
}
/**
* 题目一:写一个正则表达式,可以匹配手机号。规则: 第1位是1,第二位可以是数字3458其中之一,后面4位任意数字,最后5位为任意相同的数字。
* 题目一
*
* @param number
* 手机号码
* @return 返回匹配的第一个号码.
*/
public static String matcherPhone(String number) {
if (number == null || number.length() < 11) {
return "";
}
Pattern pattern = Pattern.compile("1[3,4,5,8]\\d{4}([0-9])\\1{4}");
Matcher matcher = pattern.matcher(number);
String phone = "";
if (matcher.find()) {
int gc = matcher.groupCount();
if (gc > 0) {
phone = (matcher.group(0));
}
}
return phone;
}
/**
* 题目二:编写程序,打印1到100之内的整数,但数字中包含7的要跳过,例如:17、27、71、72
*/
public static void showNum() {
for (int i = 0; i <= 100; i++) {
String temp = Integer.toString(i);
if (temp.indexOf("7") == -1) {
System.out.print(i+",");
}
}
System.out.print("\n");
}
/**
* 题目三:编写程序,从一个字符串中按字节数截取一部分,但不能截取出半个中文,例如:从“hello枷哇”中截取2个字节是“he,截取6个字节也要是
* "hello",而不要出现半个中文。
*
* @param text
* @param length
* @return
*/
public static String substring(String text, int length) {
if (text == null) {
return null;
}
StringBuilder sb = new StringBuilder();
int currentLength = 0;
try {
for (char c : text.toCharArray()) {
currentLength += String.valueOf(c).getBytes("GB2312").length;
if (currentLength <= length) {
sb.append(c);
} else {
break;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return sb.toString();
}
}
复制代码
PS:好想报android班 可惜技术和积分都不够呀~~新的一周开始了,大家加油~~~
作者:
thoris
时间:
2015-4-12 23:50
居然都会还说技术不够。。。我只会第二题
作者:
label
时间:
2015-4-13 00:20
刚好学习下了
作者:
黑马TYR
时间:
2015-4-13 00:29
慢慢学来
作者:
luoriver
时间:
2015-5-4 17:00
代码不错
作者:
luoriver
时间:
2015-5-4 17:01
代码不错
作者:
鸡脑壳
时间:
2015-5-4 22:41
0.0 学到新东西了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2