您的位置:首页 > 其它

2016年1月16日 关于String类…

2016-03-15 21:29 295 查看
public class StringAIPIDemo01 {
public static void main(String args[]){
String str="hello";//通过直接赋值的方式
char c=str.charAt(1);//取出字符串中指定位置的字符
System.out.println(c);
}
}
运行结果
h

将字符串转换为字符数组
将全部的字符数组转换为字符串
public class StringAIPIDemo02 {
public static void main(String args[]){
String str="hello world !!";//通过直接赋值的方式
char c[]=str.toCharArray();//将字符串转换为字符数组
for(int i=0;i
System.out.print(c[i]+"|");
}
String str1=new String(c);//将全部的字符数组转换为字符串
String str2=new String(c,0,5);//将0~5的字符数组转换为字符串
System.out.println("\n"+str1);
System.out.println(str2);
}
}
运行结果:
h|e|l|l|o| |w|o|r|l|d| |!|!|
hello world !!
hello

将全部字符串转换为byte数组
public class StringAIPIDemo03 {
public static void main(String args[]){
String str="hello world !!";//通过直接赋值的方式
byte b[]=str.getBytes();//将全部字符串转换为byte数组
String str1=new String(b);//将全部的byte数组转换为字符串
String str2=new String(b,0,5);//将0~5的byte数组转换为字符串
System.out.println(str1);
System.out.println(str2);
}
}

判断开头结尾是否为指定的字符
public class StringAIPIDemo04 {
public static void main(String args[]){
String str="** hello world ##";//通过直接赋值的方式
System.out.println(str.endsWith("##"));//判断是否以##结尾
System.out.println(str.startsWith("**"));//判断是否以**开头
}
}
运行结果:
true
true

替换操作
public class StringAIPIDemo05 {
public static void main(String args[]){
String str="** hello world ##";//通过直接赋值的方式
String Newstr=str.replaceAll("l", "e");//将l换为e
System.out.println(Newstr);
}
}

截取操作
public class StringAIPIDemo06 {
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);
}
}
运算结果
world !
hello
//这里需要注意的是第一种截取是从6开始截取,而第二种是从0截取到5.如下图所示
hello world !!
0123456789

拆分字符串
public class StringAIPIDemo07 {
public static void main(String args[]){
String str="hello world!";//通过直接赋值的方式
String s[]=str.split(" ");//拆分空格两边的
for(String st:s){
System.out.println(st);
}
}
}
运行结果:
hello
world!

查找操作:
public class StringAIPIDemo08 {
public static void main(String args[]){
String str="hello world!";//通过直接赋值的方式
System.out.println(str.contains("hello"));
System.out.println(str.contains("ohh"));
}
}
运行结果:
true
false

第二种方法查找(更加常用!)
public class StringAIPIDemo09 {
public static void main(String args[]){
String str="hello world!";//通过直接赋值的方式
System.out.println(str.indexOf("hello"));
System.out.println(str.indexOf("ohh"));
if(str.indexOf("ohh")!=-1){
System.out.println("查到所需内容");
}else{
System.out.println("未查到!");
}
}
}
运行结果:
0
-1
未查到!

查找时还可以规定从第几位找
public class StringAIPIDemo10 {
public static void main(String args[]){
String str="hello world!";//通过直接赋值的方式
System.out.println(str.indexOf("h"));
System.out.println(str.indexOf("h",5));//从第6未开始查找
if(str.indexOf("o")!=-1){
System.out.println("查到所需内容");
}else{
System.out.println("未查到!");
}
}
}
运行结果:
0
-1
查到所需内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: