一.键盘输入一个字符串,并且统计其中各种字符串出现的次数
思路:
- 键盘输入,用Scanner
- 接收字符串,用String str = sc.next()
- 定义四个变量, 分别代表四个字符各自出现的次数
- 需要对字符串一个字一个字检查,String–>char[], 方法就是toCharArray()
- 遍历char[]字符数组,对当前的字符种类进行判断,用四个变量进行++操作
- 打印输出四个变量
public class Demo09StringCount
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String input = sc.next(); //接收字符串
int countUpper = 0;//大写字母出现次数
int countLower = 0;//小写字母出现次数
int countNumber = 0; //数字出现次数
int countOther = 0; //其他字符出现次数
char[] charArray = input.toCharArray();
for(int i = 0; i < charArray.length; i++)
{
char ch = charArray[i];
if('A' <= ch && 'Z' >= ch )
{
countUpper++;
}
else if('a' <= ch && 'z' >= ch)
{
countLower++;
}
else if('0' <= ch && '9' >= ch)
{
countNumber++;
}
else
{
countOther++;
}
}
System.out.println("大写字母有: " + countUpper + "个");
System.out.println("小写字母有: " + countLower + "个");
System.out.println("数字有: " + countNumber + "个");
System.out.println("其他字符有: " + countOther + "个");
}
}
二. 把数组{1,2,3}按照指定格式拼接成一个字符串 [EVE1#EVE2#PVP3]
思路:
- 先准备一个int[]数组,
- 定义一个方法,用来将数组变成字符串
三要素:
返回值类型 String
方法名称 fromArrayToString
参数列表 int[] - 格式 [EVE1#EVE2#PVP3]
- 调用方法,得到返回值,并打印结果字符串
public class Demo08StringPractise
{
public static void main(String[] args)
{
int [] arr = {1,2,3};
String str = fromArrayToString(arr);
System.out.println(str);
}
public static String fromArrayToString (int [] arr)
{
String str1 = "["; //开头
for(int i = 0; i <arr.length; i++)
{
if(i == arr.length - 1)
{
str1 = str1 + "PVP" + arr[i] + "]"; //尾巴
}
else
{
str1 = str1 + "EVE" + arr[i] + "#"; //中间
}
}
return str1;
}
}