java 字符串地址_Java对一个地址字符串不要省市如何处理?

如果需要效率,那么可以考虑这样:

char[] chars = str.toCharArray();

// oP: '省' 的偏移, oC: '市' 的偏移, oR: "自治区" 的偏移

int oP = -1, oC = -1, oR = -1;

char ch;

for (int i = 0; i < chars.length; i++) {

ch = chars[i];

// 一般来说 '省' 的位置会比 '市' 早出现

if (ch == '省') {

oP = i;

} else if (ch == '市') {

oC = i;

// 找到 '市' 后就可以跳出循环了

break;

} else if (ch == '自'

&& i + 2 < chars.length

&& chars[i + 1] == '治'

&& chars[i + 2] == '区') {

// "自治区" 出现的几率挺小

oR = i + 2;

}

}

if (oC != -1) {

str = str.substring(oC + 1);

} else if (oP != -1) {

str = str.substring(oP + 1);

} else if (oR != -1) {

str = str.substring(oR + 1);

}

这样的话,只需要对字符串做一次遍历,然后对原字符串做一次截断 (String.substring 调用的是 native 方法,效率不低)。

最好的情况是找到 oP/oR、oC 后按 oC 截断;

少见的情况是只找到 oP/oR 后按找到的偏移截断;

最差的情况是遍历完整个字符串,但此时就不需要截断了。

格式固定是 **省**市****的话,直接 str = str.substring(str.indexOf("市") + 1) 就好了嘛

如果是可能有一部分那就:

int offset = -1;

if ((offset = str.indexOf("市")) != -1) {

str = str.substring(offset + 1);

} else if ((offset = str.indexOf("省")) != 1) {

str = str.substring(offset + 1);

}

一般来说不会有 **市**省**** 的写法吧,所以先判断有没有市,有就直接截断,没有再看看有没有省,有就截断。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,根据您的问题,我可以给您提供以下代码: ``` 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); ``` 希望这个代码能够对您有所帮助。如果您还有其他问题,请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值