String练习一
第一题:
需求:统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数,其他字符出现的次数
ABCDEabcd123456!@#$%^
大写字符数值:65-90
小写字符数值:97-122
数字字符数值:48-57
public class TestDemo5 {
public static void main(String[] args) {
int upCount = 0;
int lowCount = 0;
int mathCount = 0;
int otherCount = 0;
String str = "ABCDEabcd123456!@#$%^";
for(int i=0;i<str.length();i++) {
char c = str.charAt(i);
if(c>=65 && c<=90) {
upCount++;
}else if(c>=97 && c<=122) {
lowCount++;
}else if(c>=48 && c<=57) {
mathCount++;
}else {
otherCount++;
}
}
System.out.println("大写字符的个数:"+upCount);
System.out.println("小写字符的个数:"+lowCount);
System.out.println("数字字符的个数:"+mathCount);
System.out.println("其它字符的个数:"+otherCount);
}
}
运行结果:
第二题:
需求:把数组中的数据按照指定格式拼接成一个字符串
举例:
int[] arr = {1,2,3};
输出结果:
“{1,2,3}”
public class TestDemo6 {
public static void main(String[] args) {
int[] arr = {1,2,3};
String startStr = "[";
String contentStr = "";
for(int i=0;i<arr.length;i++) {
contentStr = contentStr + String.valueOf(arr[i]);
if(i!=arr.length-1) {
contentStr = contentStr + ",";
}
}
String endStr = "]";
String result = startStr + contentStr + endStr;
System.out.println(result);
}
}
运行结果:
第三题:
需求:把字符串反转
举例:键盘录入"abc"
输出结果:“cba”
import java.util.Scanner;
public class TestDemo7 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String content = scanner.next();
char[] array = content.toCharArray();
for(int i = 0;i<array.length/2;i++) {
char temp = array[i];
array[i] = array[array.length-i-1];
array[array.length-i-1] = temp;
}
String result = new String(array);
System.out.println(result);
}
}
运行结果:
第四题:
统计大串中小串出现的次数
大串:Adcddkiqooqkdddleef
小串:dd
public class TestDemo8 {
public static void main(String[] args) {
String str = "ddcddkiqooqkdddleef";
String subStr = "dd";
int count = 0;
for(int i=0;i<str.length();i++) {
int j = 0;
boolean flag = true;
int bi = i;
while(j<subStr.length()) {
char c1 = subStr.charAt(j);
if(c1 == str.charAt(bi)) {
j++;
bi++;
}else {
flag = false;
break;
}
}
if(flag) {
count++;
}
}
System.out.println("小串出现的次数"+count);
}
}
运行结果: