java41字符串的方法

2019.8.7全部回顾完毕
收获:搞懂了以前不理解的内容
学会了Markdown语法
1.

将首字母变大写

public class _02将首字母变大写 {
public static void main(String[] args) {
	//1.截取第一个字母
	String n = "myxq";
	String res = n.substring(0, 1);
	//2.将第一个字母变大写
	String res1 = res.toUpperCase();
	//2.截取第一个字母以后的内容
	String res2 = n.substring(1, 4);
	//3.将两边字母结合
	System.out.println(res1+res2);
}
}

2.去除字符串中的空格

public static void main(String[] args) {
	String a = "";
	String b = null;
	String c = " my xq";
	//去除首尾的空格
	String c2 = c.trim();
	System.out.println(c2);
	//去除中间的空格(实则为去掉所有的空格)
	String c3 = c.replace(" ", "");
	System.out.println(c3);
【my xq
myxq】

3.####设计字符串是否为空的工具类
工具类:要不设计成单例,要不设计成静态方法。
(工具类中创建对象是没有意义的,所以干脆私有化构造器)
类的命名:******utils
在别的类中调用时,类名.方法名

public class StringUtils {
	StringUtils(){
		
	}
//判断字符串是否为空,空false;
	static Boolean hasLength(String str) {
		return str != null && ! "".equals(str.trim());
	}
}

在别的类中调用时,
	System.out.println(StringUtils.hasLength(""));

4.字符拼接上的性能比较:
String < StringBuffer < StringBuilder
【因为可变字符串内容改变时不需要创建新的内存地址】
String拼接直接+= , StringBuilder和stringBuffer是通过append拼接

字符串安全性比较:StringBuilder < StringBuffer
但StringBuffer的安全性更高一些,原因:在append方法中存在synchronized(加锁)

5.StringBuilder的相关信息
容量:只有16个字符的容量,当容量不够时,会自动扩容。扩充成 x *2+2;
可变字符串实际上是字符数组

public class Stringbuilder {
public static void main(String[] args) {
	StringBuilder s = new StringBuilder();
	s.append("1315");
	System.out.println(s.capacity());
}
}
【16】
public class Stringbuilder {
public static void main(String[] args) {
	StringBuilder s = new StringBuilder();
	s.append("15125sgfgsfgsg121315");
	System.out.println(s.capacity());
}
}
【34】

删除指定位置数据

	s.deleteCharAt(2);
	System.out.println(s);
【1525sgfgsfgsg121315】

链式编程

	s.append("1316").append(156.2);//append中可以加任何类型的数据
【1316156.2】

可变字符串变不可变字符串
String s2 = s.toString();
不可变字符串变可变字符串
StringBuilder s = new StringBuilder("15");
将字符串倒序输出
System.out.println(s.reverse());
字符串总结

posted @ 2019-08-07 19:46  不断寻找  阅读(156)  评论(0编辑  收藏  举报