Java程序检查字符串中的URL
可以创建一个程序来检查字符串是否为正确的URL。URL的示例如下所示-
String = https://www.wikipedia.org/ The above string is a valid URL
演示该程序的程序如下。
示例
import java.net.URL;
public class Example {
public static boolean check_URL(String str) {
try {
new URL(str).toURI();
return true;
}catch (Exception e) {
return false;
}
}
public static void main(String[] args) {
String str = "http://www.wikipedia.org/";
System.out.println("String = " + str);
if (check_URL(str))
System.out.println("The above string is a URL");
else
System.out.println("The above string is not a URL");
}
}输出结果
String = http://www.wikipedia.org/ The above string is a URL
现在让我们了解上面的程序。
在函数check_URL()中,创建一个URL对象。如果在创建对象时没有异常,则返回true。否则,返回false。演示此过程的代码段如下所示。
public static boolean check_URL(String str) {
try {
new URL(str).toURI();
return true;
}catch (Exception e) {
return false;
}
}在函数中main(),字符串被打印出来。然后使用字符串str调用函数check_URL()。如果返回true,则str是URL并被打印,否则str不是URL并被打印。演示此过程的代码段如下所示。
public static void main(String[] args) {
String str = "http://www.wikipedia.org/";
System.out.println("String = " + str);
if (check_URL(str))
System.out.println("The above string is a URL");
else
System.out.println("The above string is not a URL");
}热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短