java学习之字符串

java学习之字符串

  1. 字符串的比较
public class Stringdome {
    public static void main(String[] args) {
        String str ="hello";
        String str1= new String ("hello");
        System.out.println(str==st1);
    }
}
public class Stringdome {
    public static void main(String[] args) {
        String str ="hello";
        String str1= new String ("hello");
        System.out.println(str.equals(str1));
    }
}

这是字符串通过==str.equals比较字符串是否相同
两者的不同点在于前者是比较字符串的地址,而后者是比较字符串的内容

所以前者输出的是false后者输出的是true

image

好习惯
开发中尽量用String str="hello";这类直接赋值的语句,不要用String str1=new String("hello");这类重新开辟空间的赋值语句

  1. 字符串内容不可更改
    public static void main(String[] args) {
        String str ="hello";
        str=str+"World";
        System.out.println(str);
    } 

虽然输出的结果是helloWorld但是内存地址已经改变了

image

  1. 字符串常用的方法

    • 字符串长度:length()
    • 字符串转换数组:toCharArray()
    • 从字符串中取出指定位置的字符:charAt()
    • 字符串与byte数组的转换:getByte()
    • 过滤字符串中存在的字符:indeOf() 可用于寻找特殊字符例如:@ 敏感文字等等
    • 去掉字符串的前后空格:trim()
    • 从字符串中取出子字符串:subString()
    • 大小写转换:toLowerCase() toUpperCase()
  2. StringBuffer的使用
    认识StringBuffer
    本身也是操作字符串,但是和String不同,StringBuffer是可更改的,且不需开辟新的内存空间,作为一个操作类,必须要通过实例化操作

public class Stringdome {
    public static void main(String[] args) {
        StringBuffer sb =new StringBuffer();
        sb.append("i love ");
        System.out.println(sb.toString());
        tell(sb);
        System.out.println(sb.toString());
        }
        public static void tell(StringBuffer s)
        {
            s.append("jikexueyuan");
    }
}

StringBuffer的常用方法

  • 尾部追加:append()
  • 插入:insert()
  • 代替:replace()
  • 索引子字符串的第一个字符:indexOf()
  1. StringBuilder的使用
image
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容