码迷,mamicode.com
首页 > 编程语言 > 详细

关于JAVA的String类的一些方法

时间:2015-10-23 21:32:31      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

一、得到字符串对象的有关信息

1.通过调用length()方法得到String的长度.

String str=”This is a String”;

int len =str.length();

2.StringBuffer类的capacity()方法与String类的 length()的方法类似,但是她测试是分配给StringBuffer的内存空间的大小,而不是当前被使用了的内存空间。

3.如果想确定字符串中指定字符或子字符串在给定字符串的位置,可以用 indexOf()和lastIndexOf()方法。

String str=”This is a String”;

Int index1 =str.indexOf(“i”);   //index=2

Int index2=str.indexOf(‘i’,index+1);   //index2=5

Int index3=str.lastIndexOf(“I”);   //index3=15

Int index4=str.indexOf(“String”);  //index4=10

二、String 对象的比较和操作

1.String 对象的比较

String类的equals()方法用来确定两个字符串是否相等。

String str=”This is a String”;

Boolean result=str.equals(“This is another String “);

//result=false

2.String对象的访问

A、方法charAt()用以得到指定位置的字符。

String str=”This is a String”;

char chr=str.charAt(3); //chr=”i”

B、方法getChars()用以得到字符串的一部分字符串

public void getChars(int srcBegin,int srcEnd,char[]dst,int dstBegin)

String str=”This is a String”;

Char chr =new char[10];

Str.getChars(5,12,chr,0);  //chr=”is a St”

C、subString()是提取字符串的另一种方法,它可以指定从何处开始提取字符串以及何处结束。

3.操作字符串

A、replace()方法可以将字符串中的一个字符替换为另一个字符。

String str=”This is a String”;

String str1=str.replace(‘T’,‘t’); //str1=”this is a String”

B、concat()方法可以把两个字符串合并为一个字符串。

String str=”This is a String”;

String str1=str.concat(“Test”); //str1=”This is a String Test”

C、toUpperCase()和toLowerCase()方法分别实现字符串大小写的转换。

String str=”THIS IS A STRING”;

String str1=str.toLowerCase(); //str1=”this is a string”;

D、trim()方法可以将字符串中开头和结尾处的空格去掉.

String str=”This is a String   “;

String str1=str.trim();   // str1=”This is a String”

E、String 类提供静态方法valueOf(),它可以将任何类型的数据对象转换为一个字符串。如

System.out.println(String,ValueOf(math,PI));

关于JAVA的String类的一些方法

标签:

原文地址:http://www.cnblogs.com/420Rock/p/4905558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!