鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(补2012.8.25)
本章内容
1 字符串相关类(String,StringBuffer)
2 基本数据类型包装类
3 Math类
4 File类
5 枚举类
String类
java.lang.String 类代表 不可变 的字符序列
“xxxxx”为该类的一个对象
String类的常见构造方法:见api文档
String类常用的方法
public char charAt(int index)
返回字符串中第index个字符
public int length()
返回字符串长度
public int indexOf(String str)
返回字符串中出现str的第一个位置
public int indexOf(String str, int fromIndex)
返回字符串中从fromIndex开始出现str的第一个位置
public boolean equalsIgnoreCase(String another)
比较字符串与another是否一样(忽略大小写)
public String replace(char oldChar,char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startWith(String prefix)
判断字符串是否以prefix字符串开头
public boolean endWith(String suffix)
判断字符串是否以suffix字符串结尾
public String toUpperCase()
返回一个字符串为该字符串的大写形式
public String toLowerCase()
返回一个字符串为该字符串的小写形式
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的子字符串
public String substring(int beginIndex, int endIndex)
返回该字符串从beginIndex开始到endIndex结尾的子字符串
public String trim()
返回将该字符串去掉开头和结尾空格后的字符串
//TestString.java
public class TestString {
public static void main(String args[]) {
String s1 = "hello"; //hello在datasegment区域,
String s2 = "world";
String s3 = "hello"; //s3和s1指向同一个"hello"
System.out.println( s1 == s3);
s1 = new String("hello"); //hello在heap区域
s2 = new String("hello"); //new 出一个新hello
System.out.println(s1 == s2);
System.out.println(s1.equals(s2)); //String重写了equals方法
char c[] = {'s', 'u', 'n', ' ', 'j', 'a', 'v', 'a'};
String s4 = new String(c);
String s5 = new String(c, 4, 4);
System.out.println(s4);
System.out.println(s5);
//String s1 = "java sun"; 已经定义过啦
//String s2 = "Java Sun";
s1 = "java sun";
s2 = "Java Sun";
System.out.println(s1.charAt(1));
System.out.println(s2.length());
System.out.println(s1.indexOf("java"));
System.out.println(s1.indexOf("Java"));
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
String s = "我是程序员,我在学java";
String sr = s.replace("我", "你");
System.out.println(sr);
s = "Welcome to Java World!";
s1 = " sun java ";
System.out.println(s.startsWith("Welcome")); //注意是starts和ends
System.out.println(s.endsWith("!")); //!和 World! 都是true
String sL = s.toLowerCase();
String sU = s.toUpperCase();
System.out.println(sL);
System.out.println(sU);
String subS = s.substring(11);
System.out.println(subS);
String sp = s1.trim();
System.out.println(sp);
}
}