String 类
- 字符串是常量,创建之后不可改变
- 字符串字面值存储在字符串池中,可以共享。
- String s=“hello”;产生一个对象,字符串池中存储;
- String s= new String(“Hello”);//产生两个对象,堆、池各一个
常用方法
-
public int length():
返回字符串的长度; -
public char charAt(int index):
根据下标获取字符。 -
public boolean contains(String str):
判断当前字符串中是否包含str。 -
public char[] toCharArray():
将字符串转换为数组。 -
public int indexOf(String str)
查找str首次出现的下标,存在,则返回该下标;不存在,则返回-1。 -
public int lastIndexof(String str)
查找str最后一次出现的下标 -
public String toUpperCase():
将小写转成大写 -
public boolean endWith(String str) :
判断字符串是否以str结尾。 -
public String trim():
去掉字符串前后的空格 -
public String replace(char oldChar,char newChar)
将旧字符串替换成新字符串 -
public String [] split(String str):
根据str做拆分 -
补充两个方法equals、compare();比较大小
String s1="hello"; String s2="Hello"; System.out.println(s1.equals(s2)) //false System.out.println(s1.equalsIgnoreCase(s2));//true equalsIgnoreCase是忽略大小写的比较 String s3="abc";//97 String s4="xyz";//120 System.out.println(s3.compareTo(s4));//-23 相当于s3-s4
String content ="java是世界上最好的语言";
System.out.println(content.length());//15
System.out.println(content.charAt(content.length()-1));//言
System.out.println(content.contains("php")); //false
System.out.println(content.toCharArray()); //java是世界上最好的语言
System.out.println(Array.toString(content.toCharArray()); //[j, a, v, a, 是, 最, 好, 的, 语, 言]
String say = "java is the best programing language,java xiang";
String[] arr = say.split(" ");
String[] arr2 = say.split("[ ,]");
System.out.println(arr.length);//等于7 注意数组的中,没有方法,拿到的是他的属性
for (String string: arr2){
System.out.println(string)
};/* java
is
the
best
programing
language
java
xiang
*/
案例演示
需求:
已知String str="this is a text";
1.将str中的单词单独获取出来
2. 将str中的text 替换为practice
3. 在text前面插入一个easy
4.将每个单词的首字母改写为大写
public static void main(String[] args) {
String str = "this is a text";
String[] dan = str.split(" ");
System.out.println("-----将每个单词拿出来-----");
for (String i : dan) {
System.out.println(i);
}
System.out.println("-----将text替换成practice-----");
System.out.println(str.replace("text", "practice"));
System.out.println("-----在text前面插入easy-----");
System.out.println(str.replace("text", "easy test"));
System.out.println("-----每个单词改成大写-----");
for (int i = 0; i < dan.length; i++) {
char first = dan[i].charAt(0);
char upper = Character.toUpperCase(first);
System.out.println(upper+dan[i].substring(1,dan[i].length()));//从某个位置到某个位置
System.out.println(upper+dan[i].substring(1));
}
}