admin 管理员组

文章数量: 1087139


2024年4月18日发(作者:index函数和match函数怎么综合运用)

java中的string方法

一、String类

String类在包中,java使用String类创建一个字符串变量,字符串变量属于对

象。java把String类声明的final类,不能有类。String类对象创建后不能修改,由0或

多个字符组成,包含在一对双引号之间。

二、String类对象的创建

字符串声明:String stringName;

字符串创建:stringName = new String(字符串常量);或stringName = 字符串常量;

三、String类构造方法

1、public String()

无参构造方法,用来创建空字符串的String对象。

1 String str1 = new String();

2、public String(String value)

用已知的字符串value创建一个String对象。

1 String str2 = new String("asdf"); 2 String str3 = new String(str2);

3、public String(char[] value)

用字符数组value创建一个String对象。

1 char[] value = {'a','b','c','d'};

2 String str4 = new String(value);//相当于String str4 = new String("abcd");

4、public String(char chars[], int startIndex, int numChars)

用字符数组chars的startIndex开始的numChars个字符创建一个String对象。

1 char[] value = {'a','b','c','d'};

2 String str5 = new String(value, 1, 2);//相当于String str5 = new

String("bc");

5、public String(byte[] values)

用比特数组values创建一个String对象。

1 byte[] strb = new byte[]{65,66};

2 String str6 = new String(strb);//相当于String str6 = new String("AB");

四、String类常用方法

1、求字符串长度

public int length()//返回该字符串的长度

1 String str = new String("asdfzxc");

2 int strlength = ();//strlength = 7

2、求字符串某一位置字符

public char charAt(int index)//返回字符串中指定位置的字符;注意字符串中第一个字

符索引是0,最后一个是length()-1。

1 String str = new String("asdfzxc");

2 char ch = (4);//ch = z

3、提取子串

用String类的substring方法可以提取字符串中的子串,该方法有两种常用参数:

1)public String substring(int beginIndex)//该方法从beginIndex位置起,从当前字

符串中取出剩余的字符作为一个新的字符串返回。

2)public String substring(int beginIndex, int endIndex)//该方法从beginIndex位

置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回。

1 String str1 = new String("asdfzxc");

2 String str2 = ing(2);//str2 = "dfzxc"

3 String str3 = ing(2,5);//str3 = "dfz"

4、字符串比较

1)public int compareTo(String anotherString)//该方法是对字符串内容按字典顺序

进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象

比参数大则返回正整数,反之返回负整数,相等返回0。


本文标签: 字符串 创建 返回 字符 函数