【util】替换字符串中的特定字符串

时间:2023-01-20 14:54:46

需求:将一串英文数学字母开头的数据替换成阿拉伯数学数字,

例如:nineeightsevensixfivefourthreetwoonezero替换成9876543210。

思路:通过split方法,将匹配到的字符串替换成新的字符串

package demo;

import java.util.HashMap;
import java.util.Map;

import utils.StringUtil;

/**
*
* @author qq1623299667
*
*/
public class TransferStringToInteger {
public static void main(String[] args) {
String s = "nineeightsevensixfivefourthreetwoonezero";
String result = tansferStringtoInteger(s);
System.out.println(result);
}
private static String tansferStringtoInteger(String string) {
String[] stringLibary = {"zero","one","two","three","four","five","six","seven","eight","nine"};
Map<String,Integer> transferMap = new HashMap<String,Integer>();
transferMap.put("zero", 0);
transferMap.put("one", 1);
transferMap.put("two", 2);
transferMap.put("three", 3);
transferMap.put("four", 4);
transferMap.put("five", 5);
transferMap.put("six", 6);
transferMap.put("seven", 7);
transferMap.put("eight", 8);
transferMap.put("nine", 9);
for(int i=0;i<stringLibary.length;i++){
string = StringUtil.tansferString(string, stringLibary[i], transferMap.get(stringLibary[i]).toString());
}
return string;
}
}

package utils;

/**
*
* @author qq1623299667
*
*/
public class StringUtil {
public static void main(String[] args) {
String string = "葡萄吃葡萄不吐葡萄皮,不吃葡萄倒吐葡萄皮";
string = tansferString(string,"葡萄","香蕉");
System.out.println(string);
}

/**
* 将字符串中的某个字符替换成另外的字符
* @param string
* @param transKey1
* @param transKey2
* @return
*/
public static String tansferString(String string,String transKey1,String transKey2) {
String result = "";
if(string.contains(transKey1)){
String[] splitArray = string.split(transKey1);
for(int i=0;i<splitArray.length;i++){
result = result + splitArray[i] + transKey2;
}
if(!string.endsWith(transKey1)){
result = result.substring(0, result.length()-transKey2.length());
}
}
return result;
}
}

最后的结果

====================================

9876543210