示例:判斷一字符串中為什么字符類型,并統(tǒng)計(jì)個(gè)數(shù)。
解決這個(gè)問題需要遍歷數(shù)組,并且需要拿出這個(gè)字符串中的字符,那么這時(shí)就需要使用chaAt方法獲取每一個(gè)字符了。
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("數(shù)字類型=" + count1 + "字母類型的=" + count2 + "其它類型=" + count3);
}
}
獲取方法:
length():獲取字符串長(zhǎng)度方法。
charAt():獲取字符串給定腳標(biāo)的字符。如果沒有找到就會(huì)返回字符角標(biāo)越界。
indexOf(字符):獲取字符串給定字符的角標(biāo)。
indexOf(字符,起始位置):從起始位置開始查找第一次出現(xiàn)該字符的位置,如果沒找到就會(huì)返回-1;。
indexOf(短字符串):獲取短字符串第一次出現(xiàn)的位置。
indexOf(短字符串,起始位置):從起始位置開始查找第一次出現(xiàn)該短字符串的位置,如果沒找到就會(huì)返回-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():判斷給定字符串是否是該字符串的末未。