2.1、字符与字符串
|
public class StringAPIDemo01
{
public static void main(String args[])
{
String str = "hello" ;
char c = str.charAt(2) ;
System.out.println(c) ;
}
} |
|
public class StringAPIDemo02
{
public static void main(String args[])
{
String str = "hello world !!!!!#@" ;
char c[] = str.toCharArray() ;
for (int i = 0 ; i < c.length ; i++ )
{
System.out.print(c[i] + "、" ) ;
}
String str1 = new String(c) ;
String str2 = new String (c,0,5) ;
System.out.println("\n"+str1) ;
System.out.println(str2) ;
}
} |
2.2、字节与字符串
|
public class StringAPIDemo03
{
public static void main(String args[])
{
String str = "hello world !!!!!#@" ;
byte b[] = str.getBytes() ; //将字符串变为字节数组
String str1 = new String(b) ;
String str2 = new String (b,0,5) ;
System.out.println("\n"+str1) ;
System.out.println(str2) ;
}
} |
2.3、判断是否以指定的字符串开头或结尾
|
public class StringAPIDemo04
{
public static void main(String args[])
{
String str = "**hello world ##" ;
System.out.println(str.startsWith("**")) ;
System.out.println(str.endsWith("##")) ;
}
} |
2.4、替换操作
|-public String replaceAll(String regex,String replacement)
|
public class StringAPIDemo05
{
public static void main(String args[])
{
String str = "hello world " ;
String newStr = str.replaceAll("l","x") ;
System.out.println(newStr) ;
}
} |
2.5、字符串的截取
|
public class StringAPIDemo06
{
public static void main(String args[])
{
String str = "hello world " ;
String sub1 = str.substring(6) ; //从第六个字符开始截取
String sub2 = str.substring(0,5) ; //从第一个字符截取到第五个字符
System.out.println(sub1) ;
System.out.println(sub2) ;
}
} |
2.6、字符串的拆分
|
public class StringAPIDemo07
{
public static void main(String args[])
{
String str = "hello world " ;
String s[] = str.split(" ") ;
for (String st :s)
{
System.out.println(st) ;
}
}
} |
2.7、字符串查找
|
public class StringAPIDemo08
{
public static void main(String args[])
{
String str = "hello world " ;
System.out.println(str.contains("hello")) ; //ture
System.out.println(str.contains("aust")) ; //false
}
} |
|
public class StringAPIDemo09
{
public static void main(String args[])
{
String str = "hello world " ;
System.out.println(str.indexOf("hello")) ;
System.out.println(str.indexOf("aust")) ;
if((str.indexOf("aust")) != -1)
{
System.out.println("查找到所需的内容。");
}
}
} |
|
public class StringAPIDemo10
{
public static void main(String args[])
{
String str = "hello world " ;
System.out.println(str.indexOf("hello")) ;
System.out.println(str.indexOf("hello " , 6)) ;
}
} |
2.8、字符串的其他操作
|
public class StringAPIDemo11
{
public static void main(String args[])
{
String str = " hello world " ;
System.out.println(str.trim()) ;
System.out.println(str.trim().length());
System.out.println(str.trim().toUpperCase()) ;
}
} |

















