`
ss1
  • 浏览: 77862 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

String类提供处理字符串的方法

阅读更多
String类提供处理字符串的方法
2009-07-24 11:50

package linhui1;

public class P3 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "welcome to java";
String s2=s1;
String s3=new String("welcome to java");
String s4=s3.intern();
System.out.println(s1==s2);//1
System.out.println(s1==s3);//2
System.out.println(s1.equals(s2));//3
System.out.println(s2.equals(s3));//4
System.out.println(s1.compareTo(s2));//5
System.out.println(s2.compareTo(s3));//6
System.out.println(s1==s4);//7
System.out.println(s1.charAt(0));//8
System.out.println(s1.indexOf('j'));//9
System.out.println(s1.indexOf("to"));//10
System.out.println(s1.lastIndexOf('a'));//11
System.out.println(s1.lastIndexOf("o",15));//12
System.out.println(s1.length());//13
System.out.println(s1.substring(5));//14
System.out.println(s1.substring(5,11));//15
System.out.println(s1.startsWith("welc"));//16
System.out.println(s1.endsWith("java"));//17
System.out.println("welcome".trim());//18
System.out.println(s1.toLowerCase());//19
System.out.println(s1.toUpperCase());//20
System.out.println(s1.replace('o','T'));//21
System.out.println(s1.replaceFirst("o", "T"));//22
System.out.println(s1.replaceAll("o","T"));//23
System.out.println(s1.toCharArray());
}

}


结果:

true    //1
false //2
true    //3
true    //4
0      //5
0      //6
true    //7
w      //8
11      //9
8      //10
14      //11
9      //12
15      //13
me to java    //14
me to        //15
true          //16
true          //17
welcome      //18
welcome to java          //19
WELCOME TO JAVA          //20
welcTme tT java          //21
welcTme to java          //22
welcTme tT java          //23
welcome to java          //24

1.通常,在一个程序中需要比较两个字符串的内容,可以尝试使用运算符==,然而,==运算符只能检测s2和s3是否指向同一个对象,不能判断是否 具有相同的内容。因而,不能使用==运算符判断两个字符串是否具有相同的内容。取而代之,可以使用equals()方法对对象的内容进行比较。

2.可以通过调用length()方法得到字符串的长度。方法s.charAt(index)可用于提取字符串s中的一个指定字符,其中index在0到s.length()-1之间。

3.可以使用charAt方法从字符串中提取单字符,使用String类中的substring方法,也可以从字符串中提取字串。substring方法有两个版本:
a. public String substring (int beginIndex,int endIndex)返回一个新的字符串,它也是改字符串的字串。字串从指定的下标的字符下标开始,扩展到字符串为endIndex-1结束的字符。
b. public String substring (int beginTndex) 一直扩展到字符串的结尾。

4. 利用indexOf()和lastIndexOf方法可以在字符串中得到一个字符串或一个字串。String类中定义了4个重载的indexOf方法和4个重载的indexOf方法。
public int indexOf(int ch)    (public int lastIndexOf(int ch))
public int indexOf(int ch,int formIndex)    (public int lastIndexOf(int ch,int endIndex))
pubilc int indexOf(String str)      (public int lastIndexOf(String str))
public int indexOf(String str,int fromIndex)    (public int lastIndexOf(String str,int endIndex))

5.字符串不是数组,但是字符串能够转换成数组,份儿亦然。使用toCharArray方法可以将字符串转换成一个字符的数组。
如:char [] chars="java".toCharArry();
因此,chars[0]为'j' ,chars[1]为'a',chars[2]为'v',chars[3]为'a'。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics