您的位置:首页 > 编程语言 > Java开发

javaAPI(Sting)

2015-07-19 11:08 218 查看
1、字符串概念: 由多个字符组成的一串数据

2、构造方法:

String s = new String();

通过字节数组创建字符串对象

String s = new String(byte[] bys);

通过字节数组创建字符串对象常用

String s = new String(byte[] bys,int index, int length)

通过字节数组一部分创建字符串对象

String s = new String(char[] chs)

通过字符数组创建字符串对象常用

String s = new String(char[] chs, int index, int length);

通过字符数组一部分创建字符串对象

String s = new String(String);

通过给构造方法传入字符串创建字符字符串对象

String s = “helloworld”

直接给字符串对象赋值常用

3、字符串的特点及面试题

1、特点及注意事项

字符串一旦被赋值,就不能改变。

注意:字符串的值不能改变,引用是可以改变的。

2、面试题

a:String s = new String(“hello”)和String s = “hello”的区别。

答:new String(“hello”)在内存中创建了1个或两个对象,为什么..

“hello”在内存中创建了0个或一个对象,为什么…

b:请写出结果:

String s1 = new String(“hello”);

String s2 = new String(“hello”);

System.out.println(s1==s2);//false

System.out.println(s1.equals(s2));//true

String s3 = new String(“hello”);

String s4 = “hello”;

System.out.println(s3==s4);//false

System.out.println(s3.equals(s4));//true

String s5 = “hello”;

String s6 = “hello”;

System.out.println(s5==s6);//true

System.out.println(s5.equals(s6));//true

c : “”和null的区别

最本质的区别是否在内存中开辟内存空间,”’会开辟内存空间,而null不会,在开发的时候要养成良好的习惯用null

4、String类——成员方法

1、判断功能

boolean equals(Object obj)

判断字符串的内容是否相同,区分大小写

boolean equalsIgnoreCase(String str)

判断字符串的内容是否相同,忽略大小写

boolean contains(String str)

判断字符串对象是否包含给定的字符串

boolean startsWith(String str)

判断字符串对象是否是以给定的字符串开始

boolean endsWith(String str)

判断字符串对象是否是以给定的字符串结束

boolean isEmpty()

判断字符串对象是否为空,注意是数据

2、获取功能

int length()

获取字符串长度

char charAt(int index)

返回字符串中给定索引处的字符

int indexOf(int ch)

返回指定字符在此字符串中第一次出现的索引

int indexOf(String str)

返回指定字符串在此字符串中第一次出现的索引

int indexOf(int ch,int fromIndex)

返回指定字符在此字符串中第一次出现的索引,从指定位置开始

int indexOf(String str,int fromIndex)

返回指定字符串在此字符串中第一次出现的索引,从指定位置开始

String substring(int start)

截取字符串,返回从指定位置开始截取后的字符串,原字符串长度不变

String substring(int start,int end)

截取字符串,返回从指定位置开始到指定位置结束,截取后的字符串原字符串长度不变

//如果start=0,end=该字符串的长度,那么返回的是原对象,否则返回新对象

3、转换功能

byte[] getBytes()

把字符串转换成字节数组

char[] toCharArray()

把字符串转换成字符数组

static String copyValueOf(char[] chs)

把字符数组转换成字符串

底层调用new String(char[] chs)

static String valueOf(char[] chs)

把字符数组转换成字符串

底层调用new String(char[] chs)

static String valueOf(任意类型 变量名)

把任意类型转换成字符串

String toLowerCase()

把字符变成小写原字符串不变

String toUpperCase()

把字符编程大写原字符串不变

String concat(String str)

字符串链接原字符串不变

4、其他功能

String replace(char oldChar,char newChar)

替换功能原字符串不变

String replace(String oldString,String newString)

替换功能原字符串不变

String[] split(String str)

切割功能原字符串不变

字符串的split方法中的字符串

String trim()

去除字符串两端空格原字符串长度不变

int compareTo(String str)

字典顺序比较功能

int compareToIgnoreCase(String str)

字典顺序比较功能
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: