- 字符串与字符数组的转换
toCharArray()<—>String(char[] c)..
public class StringAPIDemo01{
public static void main(String args[]){
String str1="hello";
char c[]=str1.toCharArray();
for(int i=0;i<c.length;i++){
System.out.print(c[i]+"\t");
}
System.out.println();
String str2=new String(c);
String str3=new String(c,0,3);
System.out.println(str2);
System.out.println(str3);
}
}
public class StringAPIDemo02{
public static void main(String args[]){
String str1="hello";
System.out.println(str1.charAt(1));
}
}
- 字符串与byte数组转换
getBytes()<—>String(byte[] b)..
public class StringAPIDemo03{
public static void main(String args[]){
String str1="hello";
byte b[]=str1.getBytes();
for(int i=0;i<b.length;i++){
System.out.print(b[i]+"\t");
}
System.out.println(new String(b));
System.out.println(new String(b,1,3));
}
}
public class StringAPIDemo04{
public static void main(String args[]){
String str1="hello Lixinghua";
System.out.println("\""+str1+"\"的长度为:"+str1.length());
}
}
public class StringAPIDemo05{
public static void main(String args[]){
String str1="abcdefgcgh";
System.out.println(str1.indexOf("c"));
System.out.println(str1.indexOf("c",3));
System.out.println(str1.indexOf("x"));
}
}
public class StringAPIDemo06{
public static void main(String args[]){
String str1=" hell o ";
System.out.println(str1.trim());
}
}
public class StringAPIDemo07{
public static void main(String args[]){
String str1="hello world";
System.out.println(str1.substring(6));
System.out.println(str1.substring(0,5));
}
}
public class StringAPIDemo08{
public static void main(String args[]){
String str1="hello world";
String s[]=str1.split(" "|"\t");
for(String str:s){
System.out.println(str);
}
}
}
- 字符串的大小写转换
toUpperCase()<—>toLowerCase()
public class StringAPIDemo09{
public static void main(String args[]){
System.out.println("将\"hello world\"转成大写:"+"hello world".toUpperCase());
System.out.println("将\"HELLO WORLD\"转成小写:"+"HELLO WORLD".toLowerCase());
}
}
- 判断是否以指定的字符串开头或结尾
startsWith()<—>endsWith()
public class StringAPIDemo10{
public static void main(String args[]){
String str1="**HELLO";
String str2="Hello**";
if(str1.startsWith("**")){
System.out.println("(**HELLO)以**开头");
}
if(str2.endsWith("**")){
System.out.println("(Hello**)以**结尾");
}
}
}
- 不区分大小写进行字符串比较
equalsIgnoreCase()
public class StringAPIDemo11{
public static void main(String args[]){
String str1="HELLO";
String str2="hello";
System.out.println("\"HELLO\" equals \"hello\""+str1.equals(str2));
System.out.println("\"HELLO\" equalsIgnoreCase \"hello\""+str1.equalsIgnoreCase(str2));
}
}
public class StringAPIDemo12{
public static void main(String args[]){
String str="hello";
String newStr=str.replaceAll("l","x");
System.out.println("替换之后的结果为:"+newStr);
}
}
-
从头开始查找指定的字符串位置,返回值不为-1表示找到了查询内容。
int indexOf(String str)
-
格式化字符串。
String.format(format,item1,item2,…)