示例:判断一字符串中为什么字符类型,并统计个数。
解决这个问题需要遍历数组,并且需要拿出这个字符串中的字符,那么这时就需要使用chaAt方法获取每一个字符了。
public class StringDemo {
public static void main(String[] args) {
String s = "lishuai23461489o2u4082093u4rjiklahdjhkj4782154!@#$!#$@#%$@#$";
int count1 = 0;
int count2 = 0;
int count3 = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
count1++;
} else if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
count2++;
} else {
count3++;
}
}
System.out.println("数字类型=" + count1 + "字母类型的=" + count2 + "其它类型=" + count3);
}
}
获取方法:
length():获取字符串长度方法。
charAt():获取字符串给定脚标的字符。如果没有找到就会返回字符角标越界。
indexOf(字符):获取字符串给定字符的角标。
indexOf(字符,起始位置):从起始位置开始查找第一次出现该字符的位置,如果没找到就会返回-1;。
indexOf(短字符串):获取短字符串第一次出现的位置。
indexOf(短字符串,起始位置):从起始位置开始查找第一次出现该短字符串的位置,如果没找到就会返回-1;。
public class StringDemo {
public static void main(String[] args) {
String s = "lishuailishuailishuailishuai";
String sub = "li";
int index = 0;
int count = 0;
while ((index = (s.indexOf(sub, index))) != -1) {
count++;
index = index + sub.length();
}
System.out.println(count);
}
}
substring(int beginIndex, int endIndex):截取一段字符串。
获取方法:
contains():判断给定字符串是否在该字符串中。
endsWith():判断给定字符串是否是该字符串的末未。