目录
一:字符串去除前后空格,(一般在输入账号和密码时使用)
二:字符串去除最后一位
三:截取字符串
四:字符串替换:
public static String trim(String str){
return (str == null ? "" : str.trim());
}
其中"str == null ? "" : str.trim()"采用三目运算符,它是这样执行的:如果str == null为真,则表达式取 "" 值,否则取 str.trim() 值.
//测试
public static void main(String[] args) {
System.out.println(trim(" 123 "));
}
//打印:123
public static String substring_1(String str){
return (str == "" || str ==null ? "" : str.substring(0,str.length() - 1));
}
//测试
public static void main(String[] args) {
System.out.println(substring_1("12,32,43,"));
}
//打印:12,32,43
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end) {
if (str == null) {
return "";
}
if (end < 0) {
end = str.length() + end;
}
if (start < 0) {
start = str.length() + start;
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return "";
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
final成员变量表示常量,只能被赋值一次,赋值后值不再改变。
//测试
public static void main(String[] args) {
System.out.println(substring("12,32,43,", 0,1));
}
//打印:1
/**
* @Description: 字符串替换
* @param strTmps 待处理字符串
* @param strTmp 需替换字符串
* @param str 替换字符串
*/
public static String replaceAll(String strTmps,String strTmp, String str) {
return (strTmps == null || strTmp == null || str == null ? "" : strTmps.replaceAll(strTmp, str)) ;
}
//测试
public static void main(String[] args) {
System.out.println(replaceAll("ssdssd","sd", "s"));
}
//打印:ssss
/**
* @Description: 字符串替换第一次出现的
* @param strTmps 待处理字符串
* @param strTmp 需替换字符串
* @param str 替换字符串
*/
public static String replaceFirst(String strTmps,String strTmp, String str) {
return (strTmps == null || strTmp == null || str == null ? "" : strTmps.replaceFirst(strTmp, str)) ;
}
//测试
public static void main(String[] args) {
System.out.println(replaceFirst("ssdssd","sd", "s"));
}
//打印:ssssd
才疏学浅 ,请多指教 !
参考:final关键字:https://www.cnblogs.com/xiaoxi/p/6392154.html
三目运算符:https://www.cnblogs.com/jesonjason/p/5023040.html
字符替换:https://www.cnblogs.com/shuilangyizu/p/6612240.html