String类的常用方法
java.lang.String Class
在Java中,存储和处理字符串等相关功能的实现,用String类
String(String original);
int length();
char charAt(int index);
boolean equals(Object anObject);
int indexOf(int ch);
int indexOf(String str);
static String valueOf(type b);
1 public class StringClassDemo{ 2 public static void main(String[] args){ 3 String strHello = new String("hello");//字符串初始化方法1 4 Sring strWorld = "World";//字符串初始化方法2 5 6 strWorld = new string("hello"); 7 8 if(strHello == strWorld){//==比较的是字符串的引用是否相等 9 system.out.println("The strings are equivalent according to =="); 10 }else{ 11 system.out.println("The strings are not equivalent according to =="); 12 } 13 strWorld = "World"; 14 15 if(strHello.length() != strWorld.length()){ 16 system.out,println("not"); 17 }else{ 18 system.out.println("equal in length"); 19 } 20 21 if(strHello.equals(strWorld)){//equals方法比较的是字符串的内容是否相等 22 system.out.println("The strings are equivalent according to the method equals()"); 23 }
1 system.out,println(strHello.charAt(2));//获取当前字符串某一指定位置的一个字符 2 system.out,println(strWorld.indexOf("or"));//定位“or”在字符串中第一次出现的位置 3 system.out,println((strWorld + strHello).indexOf("o", 5));//用+进行字符串连接 4 5 String strValues; 6 strValues = String.valueOf(5.87);//"5.87" 7 strValues = String.valueOf(true);//"true"
24 }
25 }