用正则表达式写:
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class hdu_IP计算2206 { public static void main(String[] args) { Scanner sc= new Scanner(System.in); String s; while(sc.hasNext()){ s = sc.nextLine(); Pattern p = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); Matcher m = p.matcher(s); if(m.find()) System.out.println("YES"); else System.out.println("NO"); } } }
C/C++:
#include<stdio.h> int main(){ char str[102],tmp[102],a[4],b[4],c[4],d[4]; while(gets(str)) { tmp[0]='\0'; if(sscanf(str,"%3[0-9].%3[0-9].%3[0-9].%3[0-9]%s",a,b,c,d,tmp)==4&&!tmp[0]) { int a,d; sscanf(str,"%d.%d.%d.%d",&a,&b,&c,&d); if(a<256&&b<256&&c<256&&d<256) puts("YES"); else puts("NO"); } else puts("NO"); } return 0; }原文链接:https://www.f2er.com/regex/362441.html