您的位置:首页 > 其它

01_String类常用方法(1)(2)

2012-05-14 17:49 417 查看
String类常用的方法(1)

charAt

public char charAt(int index)

返回字符串第index值

length

public int length()

返回此字符串的长度。长度等于字符串中 Unicode 代码单元的数量。

indexOf

public int indexOf(String str)


返回该指数在此字符串中首次出现的指定的子字符串。返回的整数是最小值k这样: true

如果未出现该字符,则返回
-1


public int indexOf (String str,int fromindex)

返回字符串中从fromindex开始出现str的第一个位置

public boolean equalslgnoreCase(String another)

比较字符串与another是否一样(忽略大小写)

public String replace(char oldChar,char newChar)

在字符串中用newChar字符替换oldChar字符

现在用一个例子说明:String类常用的方法(1)

class Test
{
public static void main(String[] args)
{
String s1 = "Ni Hao", s2 = "ni hao";
System.out.println(s1.charAt(0));  //s  会从0这个index , index从0开始数起
System.out.println(s2.length());	//6
System.out.println(s2.indexOf("hao")); //3
System.out.println(s2.indexOf("Ni")); //-1  表示错误,没有这个字符串
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equalsIgnoreCase(s2));
//true

String s = "我是搭讪教主,我认识100个美女";
String sr =s.replace('我','你');
System.out.println(sr);
}
}


输出:

N

6

3

-1

false

true

你是搭讪教主,你认识100个美女

String类常用的方法(2)

public boolean startsWitn(String prefix)

判断字符串是否以prefix字符串开头

public boolean endsWith(String suffix)

判断字符串是否以prefix字符串结尾

public String toUpperCase()

返回一个字符串为该字符串的大写形式

public String toLowerCase()

返回一个字符串为该字符串的小写形式

public String substring(int beginIndex)

返回该字符串从beginIndex开始到结尾的子字符串

public String substring(int beginIndex,int endIndex)

返回该字符串从beginIndex开始到endIndex结尾的子字符串

public String trim()

返回将该字符串去掉开头和结尾空格后的字符串

class Test
{
public static void main(String[] args)
{
String s  = "Welcome to Java Word!";
String s1 = "  Sun java  ";
System.out.println(s.startsWith("Welcome"));
//true
System.out.println(s.endsWith("Word"));
//false
String sL =s.toLowerCase();	//Lower 转换为小写字母
String sU =s.toUpperCase();  //Upper大写
System.out.println(sL);
//welcome to java word!  返回为该字符串的小写形式
System.out.println(sU);
//WELCOME TO JAVA WORD! 返回为该字符串的大写形式

String subS = s.substring(10);   //0~从第10个字符 开始
System.out.println(subS);   // Java Word!
String sp = s1.trim();	//去掉开头和结尾空格后的字符串
System.out.println(sp);
}
}


输出:

true

false

welcome to java word!

WELCOME TO JAVA WORD!

Java Word!

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