java基础八:字符串

来源:互联网 发布:sql server语句 编辑:程序博客网 时间:2024/06/01 10:09
1、字符串:String,是一个类。创建类的实例及在java后台的处理逻辑如下:

1)创建字符串的实例:

2)从一个代码分析java后台的处理逻辑:

public static void main(String[] args) {// TODO Auto-generated method stubString Str1="abc";//创建 字符串对象并赋值String Str2="abc";String Str3=new String("abc");//类的实例就是对象String Str4=new String("abc");/*==比较的时候:1)如果是基本类型,==比较的就是值,如int i=1;int j=1;i==j返回true * 2)如果是对象,比较的就是对象的地址,比如Str3==Str4 */System.out.println(Str1==Str2);//trueSystem.out.println(Str2==Str3);//falseSystem.out.println(Str3==Str4);//false}

3)字符串常量池:

上段代码处理逻辑如下:


4)字符串类是不可变的,发生改变的是对象的引用。

如定义:String str1="abc";

5)一个对象的引用不可以同时指向多个对象,一个对象是可以被多个对象的引用指向的

6)若一个对象没有指向它的对象的引用时,只能等待GC机制,在合适的时候将它收回(JAVA的垃圾回收机制-GC)

7)一个对象的引用没有指向任何对象,也是无法使用的

<span style="font-size:12px;">String str5; System.out.println(str5);</span>

2、使用字符串API

public class StringApiDemo {public static void main(String[] args) {// TODO Auto-generated method stub//定义字符串并赋值String s="where there is will,there is way";//使用API//1、length返回字符串长度,字符串内的字符的个数System.out.println(s.length());//32//2、charAt方法从字符串里面返回某个索引位置的一个字符System.out.println(s.charAt(2));//e//3、getChars()方法,没有返回值,返回区间子字符复制到一个新的字符串中char[] c=new char[5];s.getChars(0, 4, c, 0);//将s字符串0-4位字符复制到字符数组里面        //4、equals()比较2个字符串,比较指向的字符串常量String Str1=new String("abc");String Str2=new String("abc");System.out.println(Str1.equals(Str2));//5、startsWith()判断字符串是不是以某些字符串开头System.out.println(s.startsWith("w"));//trueSystem.out.println(s.startsWith("where"));//true//6、endsWith()判断字符串是不是以某些字符串结尾System.out.println(s.endsWith("y"));//trueSystem.out.println(s.endsWith("way"));//true//7、substring(beginIndex),从beginIndex截取到最后的子字符串//substring(beginIndex, endIndex),从beginIndex截取到endIndex最后的子字符串,不包含endIndexSystem.out.println(s.substring(11));//截取s字符串索引11以后所有的子字符串System.out.println(s.substring(0, 4));//截取s字符串索引0-4的子字符串,不包含4//8、replace()方法,将字符串里面的某个字符替换为其他字符,返回替换之后字符串String ns="1,2,3,4";System.out.println(ns.replace(',', ' '));//将所有,替换为空白,一次只能替换一个字符,替换的类型是char类型//9、trim()方法 删除字符串开头和结尾的空格,返回删除空格之后的字符串String es="  1 , 2 , 3 , 4  ";System.out.println(es.trim());//返回1 , 2 , 3 , 4//10、valueOf(b)将其他类型数据转换为字符串,int i=10;String s4=i+"";//<span style="color:#FF6666;">这样在内存里创建了2个字符串,消耗了内存</span>System.out.println(String.valueOf(i));//将整型i转换为字符串}}



0 0
原创粉丝点击