String处理: 获得URL的最后一个字符串

本文介绍如何使用Java的URL类方法解析URL并获取其最后一个字符串,包括实例代码演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:获得给定字符串(标准的url),获得该url最后一个字符串。

如:http://blog.youkuaiyun.com/AndroidBluetooth可以获得AndroidBluetooth

方法很简单,使用URL类的方法。

因为url是有几部分组成,所以先获得file内容,然后使用string类的split()方法分解字符串。

实例代码:

package mark.zhang;

import java.net.MalformedURLException;
import java.net.URL;

public class LastStr {

	/**
	 * @param args
	 * @throws MalformedURLException 
	 */
	public static void main(String[] args) {
		String str = "http://blog.youkuaiyun.com/AndroidBluetooth";
		String out = getLastString(str);
		System.out.println("out content: " + out);
		
		/*String file = url.getFile();
		String protocol = url.getProtocol();
		String host = url.getHost();
		String userInfo = url.getUserInfo();
		String path = url.getPath();
		int defaultPort = url.getDefaultPort();
		int port = url.getPort();
		
		System.out.println("file: " + file);
		System.out.println("protocol: " + protocol);
		System.out.println("host: " + host);
		System.out.println("userInfo: " + userInfo);
		System.out.println("path: " + path);
		System.out.println("defaultPort: " + defaultPort);
		System.out.println("port: " + port);
		
		String[] splitStr = file.split("/");
		int len = splitStr.length;
		System.out.println("" + splitStr[len-1]);*/
	}
	
	public static String getLastString(String str) {
		URL url;
		try {
			url = new URL(str);
		} catch (MalformedURLException e) {
			return null;
		}
		
		String file = url.getFile();
		String[] splitStr = file.split("/");
		int len = splitStr.length;
		String result = splitStr[len-1];
		return result;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值