常用类

String类、StringBuffer类

  • String代表不可变的字符序列
  • "xxxxxxx"为该类的对象

举例(1)

public class Test
{
public static void main (String[] args)
{
//测试1
String s1 = "hello";
String s2 = "world";
String s3 = "hello";
System.out.println(s1 == s3);//true //测试2
s1 = new String ("hello");
s2 = new String ("hello");
System.out.println(s1 == s2);//false
System.out.println(s1.equals(s2));//true //测试3
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); //sun java
System.out.println(s5); //java
}
}
  • 测试1
  • 测试2
  • 测试3

举例(2)

public class Test
{
public static void main (String[] args)
{
String s1 = "sun java";
String s2 = "Sun Java";
System.out.println(s1.charAt(1));//u
System.out.println(s2.length());//8
System.out.println(s1.indexOf("java"));//4
System.out.println(s1.indexOf("Java"));//-1
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCaes(s2));//true String s = "我是程序员";
String sr = s.replace('我','你');
System.out.println(sr);//你是程序员
}
}
  • 说明

举例(3)

public class Test
{
public static void main (String[] args)
{
String s = "Welcome to Java World";
String s1 = " sun java ";
System.out.println(s.starstWith("Welcome"));//true
System.out.println(s.endsWith("World"));//false
String sL = s.toLowerCase();
String sU = s.toUpperCase();
System.out.println(sL);//welcome to java world
System.out.println(sU);//WELCOME TO JAVA WORLD
String subS = s.substring(11);
System.out.println(subS);//Java World
String sp = s1.trim();
System.out.println(sp);//sum java
}
}
  • 说明
04-28 07:22