去掉字符串头尾指定字符
根据传入的字符 掐头去尾
public class StringUtil {
/**
* 去掉字符串头尾指定字符
* @param source 需要处理的字符串
* @param element 指定字符
* @return
*/
public static String trimFirstAndLastChar(String source, char element) {
//判断指定字符是否出现在该字符串的第一位 是--返回下标1 否--返回下标0
int beginIndex = source.indexOf(element) == 0 ? 1 : 0;
//判断指定字符是否出现在该字符串的最后一位 是--返回出现的位置 否--返回字符长度
int endIndex = source.lastIndexOf(element) + 1 == source.length()?source.lastIndexOf(element) : source.length();
//开始截取字符串
source = source.substring(beginIndex, endIndex);
return source;
}
}
比如这样一个字符串
@Test
public void test1() {
String test = "/hello world/";
System.out.println(test);
}
打印:
/hello world/
调用这个方法
@Test
public void test1() {
String test = "/hello world/";
System.out.println(test);
String trimFirstAndLastChar = StringUtil.trimFirstAndLastChar(test, '/');
System.out.println(trimFirstAndLastChar);
}
打印:
/hello world/
hello world
可以用来根据字符 分割字符串 非常好用