Java实现短信中提取号码

Description

    提取一条短信里所有的电话号码,电话号码之间换行打印,短信的内容由用户输入。

Input

    第一行有个整数n(1≤n≤1000)表示测试用例的个数。其后的每一行中有一条短信,每一条短信中只包含字母、数字、空格、标点符号,没有回车换行符,短信的长度不超过400个英文字符。

Output

    将每条短信中的电话号码提取出来。每个号码占一行。如果该短信中没有电话号码,请输出“no phone numbers!” 每个测试用例的输出之间用一个空行隔开。

    (提示:利用数据输入读取一行信息,然后利用String的方法将字符串转换成一个字符数组,再提出数字,连续的数都可以认为是电话号码)

Sample Input

2

Mr Zhang's home phone is 073112345678, and his office phone is 87654321, his mobile phone is 13812345678

Sorry, I don't have his any phone numbers!

 

Sample Output

073112345678

87654321

13812345678

no phone numbers!

法一:

import java.util.Scanner;
public class p3 {
 public static void main(String[] args) {
 Scanner in = new Scanner(System.in);
 int n = in.nextInt(); 
 String s=in.nextLine();
 for (int j = 0; j < n; j++)
 { s = in.nextLine(); 
 boolean b = true;
 for (int i = 0; i < s.length(); i++)
 { if (s.charAt(i)>='0'&&s.charAt(i)<='9') 
 { b = false; 
 System.out.print(s.charAt(i));
 if (i == s.length() -1 || (s.charAt(i + 1) < '0' || s.charAt(i + 1) > '9')) 
 { System.out.println(); }
 } 
 } 
 if (b) 
 { System.out.println("no phone numbers!"); }
 System.out.println(); }
 } 
 }

法二:

public class p3 {
     public static void main(String[] args) {
         Scanner in = new Scanner(System.in);
         int n = in.nextInt(); 
         String s=in.nextLine();
         for (int j = 0; j < n; j++)
         { s = in.nextLine(); 
         boolean b = true;
         char str[]=s.toCharArray();
         for (int i = 0; i < s.length(); i++)
         { if (str[i]>='0'&&str[i]<='9') 
         { b = false; 
         System.out.print(str[i]);
         if (i == str.length -1 || (str[i + 1] < '0' || str[i + 1] > '9')) 
         { System.out.println(); }
         } 
         } 
         if (b) 
         { System.out.println("no phone numbers!"); }
         System.out.println(); }
         } 

 

posted on 2019-05-27 21:36  闹钟七点有点迟  阅读(441)  评论(0编辑  收藏  举报

导航