String s ="Helllo Word";
String s = new String();
String s = new String("Hello World");


String类位于java.lang包中,具有丰富的方法
计算字符串的长度、比较字符串、连接字符串、提取字符串


字符串长度:
.lenght

字符串比较
String类提供了equals( )方法,比较存储在两个字符串对象的内容是否一致
.equals()

equals和==的区别:
equals():检查组成字符串内容的字符是否完全一致、=te.
==:判断两个字符串在内存中的首地址,即判断是否是同一个字符串对象

不考虑用户名的大小写问题
使用equalsIgnoreCase()方法
使用toLowerCase()方法
使用toUpperCase( )方法


字符串连接
+
concat

字符串常用提取方法:
搜索第一个出现的字符ch(或字符串value)
public int indexOf(int ch)
public int indexOf(String value)
搜索最后一个出现的字符ch(或字符串value)
public int lastIndexOf(int ch)
public int lastIndexOf(String value)
提取从位置索引开始的字符串部分
public String substring(int index)
提取beginindex和endindex之间的字符串部分
public String substring(int beginindex, int endindex)
beginindex: 字符串的位置从0开始算;endindex: 字符串的位置从1开始算
返回一个前后不含任何空格的调用字符串的副本
public String trim()


字符串拆分:
String类提供了split()方法,将一个字符串分割为子字符串,结果作为字符串数组返回
public class Lyric {
public static void main(String[] args) {
String words="长亭外 古道边 芳草碧连天 晚风扶 柳笛声残 夕阳山外山";
String[ ] printword=new String[100];
System.out.println("***原歌词格式***\n"+words);
System.out.println("\n***拆分后歌词格式***");
printword=words.split(" "); 拆分字符串,返回值为字符串数组
for(int i=0;i<printword.length;i++){
System.out.println( printword[i] );遍历输出字符串

}
}
}

 

StringBuffer:String增强版
对字符串频繁修改(如字符串连接)时,使用StringBuffer类可以大大提高程序执行效率


创建StringBuffer对象
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer("aaa");
StringBuffer的使用
sb.toString(); //转化为String类型
sb.append("**"); //追加字符串
sb.insert (1, "**"); //插入字符串


String StringBuffer StringBuilder的区别:
String 的值是不可变的,所以每次对String的操作都会生成新的String对象,效率低下
浪费大量的优先的内存的空间,
StringBuffer 是可变类,当字符串大小超过容量时,会自动增加容量。线程安全
多线程操作字符串
StringBuilder 可变类速度更快 线程不安全 单线程操作字符串

综合而言是 String 最快
String可以赋空值

 

posted on 2021-04-06 10:08  吅^O^  阅读(46)  评论(0编辑  收藏  举报