在操作String类之前需要对其进行初始化,常见的的方式有两种:
1.使用字符串常量直接初始化一个String对象,具体代码如下:
String str1 = "abc";
2.使用String的构造方法初始化对象,具体代码如下:
String() | 创建一个内容为空的字符串 |
---|---|
String(String value) | 依据指定的字符串创建内容 |
String(char[] value) | 依据指定的字符数组创建对象 |
具体代码如下:
String str1 = new String();
String str2 = new String("abcd");
char[] charArry = new char[]{'D','E','F'};
Stirng str3 = new String(charArry);
System.out.println("a"+str1+"b");
System.out.println(str2);
System.out.print(str3);
字符串的基本操作
String s = "abcdefg";
//字符串中第一个出现的位置
System.out.println(s.charAt(0));
//第一次出现C的位置(可以是子字符串想·)
System.out.println(s.indexOf('c'));
//最后一次出现C的位置
System.out.println(s.lastIndexOf('c'));
字符串的转换操作
String s1 = "ancd";
//将字符串转为字符数组后的结果
char[] charArray = str.toCharArry();
for(int i =0;i<charArray.length.i++){
//如果不是数组的最后一个元素,在元素的后面加逗号。
if(i!= charArry.lengyh-1){
System.out.println(charArray[i]+",");
}
//数组的最后一行元素后面不加逗号。
else{
System.out.println(charArray[i]);
}
}
//将int值转换为String类型
System.out.println(String.valueOf(12));
//将字符串大写
System.out.println(String.toUpperCase());
}
字符串的替换和去除空格操作
String s = "pzyruo";
//将p替换为H
System.out.println(s.replace("p","H"));
//将字符串首尾的空格去除
System.out.println(s.trim());
//将字符串中所有空格去除
System.out.println(s.replace(" ",""));
字符串的判断操作
String s = "GameForGo";
String s2 = "Game";
//判断是否是以"Game"开头/结尾
System.out.println(s.startWith("Game"));//endWith("Game");
//判断是否包含字符串
System.out.println(s.contains("Game"));
//判断是否为空
System.out.println(s.isEmpty());
//判断两个字符串是否相等
System.out.println(s1.equals(s2));
字符串的截取与分割
String s = "123456789";
//从第五个开始截取/5到6
System.out.println(s.substring(4));//(4,6)
//字符串分割 Python比java简单
StringBuffer和String最大的区别在于它的长度和内容都是可以改变的。StringBuffer类似一个字符容器,当在其中添加或删除字符时,并不会产生新的StringBuffer对象,而String则是一个常量。
public class StringBuff {
public static void main(String[] args) {
System.out.println("1.添加---------------------------------------------");
add();
System.out.println("2.删除----------------------------------------------");
delete();
System.out.println("3.替换----------------------------------------------");
alter();
}
public static void add() {
StringBuffer sb = new StringBuffer("abcdefg");
sb.append("hijklmn");
System.out.println("添加后"+sb);
sb.insert(2, "我");
System.out.println(sb);
}
public static void delete() {
StringBuffer sb = new StringBuffer("abcdefg");
sb.delete(2, 5);
System.out.println(sb);
sb.deleteCharAt(3);
System.out.println(sb);
}
public static void alter() {
StringBuffer sb = new StringBuffer("abcdefg");
sb.replace(1, 5, "kkkk");
System.out.println(sb);
System.out.println(sb.reverse());
}
}
记录子串在字符串中出现的次数
public class StringTest {
public static void main(String[] args) {
String str = "nbakjslkdjasnbaasjlkdjnbaskdlknbaksdnbalksdlnba";
String key = "nba";
int count = getKey(str ,key);
System.out.println(count);
}
public static int getKey(String str,String key) {
int count = 0;
if(!str.contains(key)) {
return count;
}
int index = 0;
while((index = str.indexOf(key))!=-1) {
str = str.substring(index+key.length());
count++;
}
return count;
}
}