Java基础学习第二天

来源:互联网 发布:gta5ol女角色捏脸数据 编辑:程序博客网 时间:2024/05/10 12:54

1.获取字符串信息
String str = “we are boby”
str.length();//返回值是 int
2.字符串的查找
String str = “we are boby”
str.indexOf(“a”);//会从当前起始位置索引也就是从0开始
lastIndexOf(str);//改方法用于指定字符串最后一次出现索引位置
public class Text{
public static void main(String[] str){
String str = “we are boby”;
int size = str.lastIndexOf(“”);
System.out.println(size);//长度是9
}
}
3.获取指定位置的字符
public class Ref(){
public static void main(Stirng[] str){
String str = “we are boby”;
char mychar = str.charAt(5);
System.out.println(mychar);//e
}
}
4.字符串截取
subString();//通过字符串的下标来截取
Stirng str = “helloword”;
String strsub = str.subString(3);//loword
beginIndex 指定从某处开始截取
注意 空格占用一个索引位置
5.字符串替换
public class Newstr{

public static void main (Stirng[] str){    Stirng str = "address";    Stirng strNew = str.replace("a","A");//注意大小写    System.out.println(strNew);///Address;    }

}
6.判断字符串开始与结尾
public class startOfEnd{
public static main(Stirng[] str){
Stirng str1 = “215584545”;
String str2 = “545120021”
boolean b1 = str1.startWith(“2155”);//判断字符串开始是否与预期一样;
boolean b2 = str2.endsWith(“1200”);//判断字符串结尾是否与预期的一样;
}
}
7.比较俩个字符串是否相同
比较两个字符串是否相同 不能简单的用”==“ 去比较,要比较两个字符串的地址是否相同
Stirng tom = new String(“i am a student”);
Stirng jom = new Stirng(“i am a student”);
boolean b = (tom==jom);
System.out.println)(b);//false 原因是引用的地址不同 需要使用equals(); 方法

equals()
equalsIgnoreCase();是忽略了大小写的情况下比较两个字符串是否相等

public class Opinion{
public static void main(Stirng[] str){
String s1 = new String(“abc”);
String s2 = new String(“ABC”);
String s3 = new String(“abc”);
boolean b = s1.equals(s2);//false
boolean b1 = s1.equalsIgnoreCase(s2);//true
boolean b2 = s1.equals(s3);//true
}
}

0 0