java给一个地址字符串截取省市县/区信息
时间: 2024-01-24 09:03:03 浏览: 32
您好,根据您的问题,我可以给您提供以下代码:
```
String address = "北京市朝阳区望京东路2号院";
String province = "";
String city = "";
String county = "";
// 省级信息
int provinceIndex = address.indexOf("省");
if (provinceIndex != -1) {
province = address.substring(0, provinceIndex + 1);
} else {
provinceIndex = address.indexOf("自治区");
if (provinceIndex != -1) {
province = address.substring(0, provinceIndex + 3);
} else {
provinceIndex = address.indexOf("特别行政区");
if (provinceIndex != -1) {
province = address.substring(0, provinceIndex + 5);
}
}
}
// 市级信息
int cityIndex = address.indexOf("市");
if (cityIndex != -1) {
int preCityIndex = provinceIndex == -1 ? 0 : provinceIndex + 1;
city = address.substring(preCityIndex, cityIndex + 1);
} else {
cityIndex = address.indexOf("自治州");
if (cityIndex != -1) {
int preCityIndex = provinceIndex == -1 ? 0 : provinceIndex + 1;
city = address.substring(preCityIndex, cityIndex + 3);
}
}
// 县/区级信息
int countyIndex = address.lastIndexOf("区");
if (countyIndex == -1) {
countyIndex = address.lastIndexOf("县");
}
if (countyIndex != -1) {
int preCountyIndex = cityIndex == -1 ? provinceIndex + 1 : cityIndex + 1;
county = address.substring(preCountyIndex, countyIndex + 1);
}
System.out.println("省级信息:" + province);
System.out.println("市级信息:" + city);
System.out.println("县/区级信息:" + county);
```
希望这个代码能够对您有所帮助。如果您还有其他问题,请随时提出。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)