String 类
常用方法:
方法名 | 返回值+含义 |
---|---|
charAt | char charAt(int index) // 获取索引对应的字符 |
contains | boolean contains(char s) //判断字符串是否包含指定字符串,返回ture |
replace | char replace(char s,char s2)//将字符串的指定所有指定字符串全部转换成规定字符串 |
length | int length() //获取字符串的长度 |
indexOf | int indexof(int/String i)//根据字符获取第一次出现的字符索引 |
lastIndexOf | int lastIndexOf(int/String i)//返回指定字符最后一次出现的索引(第一次出现==最后一次出现,字符唯一) |
split | String[] split(String s)以指定的规则切割字符串 |
substring | String substring(int toi , int fromi)//给定字符串的起始索引值,截取字符串 |
trim | String trim() 去除字符串的前后空格 |
equals | boolean equals(object obj) //判断字符串是否一致 |
不一定常用方法:
方法名 | 返回值+含义 |
---|---|
endsWith | boolean endswith(string s) //判断是否是以规定字符结尾 |
startsWith | boolean startasWith (string s)//判断是否是以规定字符开头 |
toUpperCase | String toUpperCase() //将字符串的小写转换成大写 |
toLowerCase | String toLowerCase() //将字符串的大写转换成小写 |
compareTo | int comparaTo(String s) //比较两个字符串的大小(ascll码比较) |
concat | String concat(String s) //将指定字符串连接到字符串的末尾 |
isEmpty | boolean isEmpty() //判断字符是否为空,空返回true |
valueOf | static String valueOf(Object obj) //以指定类型返回字符串 |
替换字符串中的所有规定字符
public class NumThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入源字符串:");
String scrStr = scanner.nextLine();
System.out.println("输入要删除的字符串:");
String delStr = scanner.nextLine();
System.out.println(delString(scrStr, delStr));
}
public static int delString(String scrStr, String delStr) {
int count = 0;
int index = 0;
String re = scrStr.replace(delStr, "");
count = (scrStr.length() - re.length()) / delStr.length();
while ((index = re.indexOf(delStr)) != -1) {
// 将第一个出现的delStr的索引值向后加一,直到字符串的最后
count++;
re = re.replace(delStr, "");
index = index + delStr.length();
}
System.out.println(re);
return count;
}
}