1、输入一个字符串,统计大写、小写、数字、其他字符各有多少个。
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入一个字符串");
String zf = s.next();
int da = 0;
int xiao = 0;
int num = 0;
int fu = 0;
for (int i = 0; i < zf.length(); i++) {
char ch = zf.charAt(i);
if(ch>='a' && ch <= 'z'){
xiao++;
}else if(ch >= 'A' && ch <='Z'){
da++;
}else if(ch >= '0' && ch <= '9'){
num++;
}else {
fu++;
}
}
System.out.println("大写字母有"+da+"个");
System.out.println("小写字母有"+xiao+"个");
System.out.println("数字"+num+"个");
System.out.println("符号"+fu+"个");
}
2、把arr[]数组,转换成字符串用 【4,5,6,7,8,9】格式输出。
输入一个字符串,并反转。
public static void main(String[] args) {
int [] arr = {4,5,6,7,8,9};
System.out.println(fa(arr));
Scanner s = new Scanner(System.in);
System.out.println("请输入需要反转的字符串");
String res = s.next();
System.out.println(fa(res));
}
public static String fa(int [] arr){
String s = "[";
for (int i = 0; i < arr.length; i++) {
if(i == arr.length-1){
s += arr[i];
}else {
s += arr[i];
s += ",";
}
}
s += "]";
return s;
}
public static String fa(String s){
String res = "";
for (int i = s.length()-1; i >= 0 ; i--) {
res += s.charAt(i);
}
return res;
}
3、StringBuilder练习,使用StringBuilder 数组转换字符串
//使用StringBuilder 数组转换字符串
public static void main(String[] args) {
int [] arr = {4,5,6,7,8,9} ;
String res = fa(arr);
System.out.println(res);
System.out.println(fa(res));
}
public static String fa(int [] arr){
StringBuilder s = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
if(i == arr.length-1){
s.append(arr[i]);
}else{
s.append(arr[i]).append(", ");
}
}
String res = s.toString();
return res;
}
public static String fa(String s){
//new StringBuilder(s) new一个StringBuilder对象,并把s给他
//.reverse() 字符串反转
//toString() 转换为String 类型
return new StringBuilder(s).reverse().toString();
}
4、
1.键盘录入一个字符串
2.将该字符串变成字符数组(不能使用toCharArray()方法)
3.将字符数组中的所有大写字母变成小写字母(不能使用toLowerCase()方法)
4.如果第一位和最后一位的内容不相同,则交换
5.将字符数组中索引为偶数的元素变成’~’
6.打印数组元素的内容
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串");
String s = sc.next();
char a = ' ' ;
char [] arr = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
arr[i] = s.charAt(i);
if(arr[i] >= 65 && arr[i] <= 90){
arr[i] += 32;
}
}
if(arr[0] != arr[arr.length-1]){
a = arr[0];
arr[0] = arr[arr.length-1];
arr[arr.length-1] = a;
}
for (int j = 0; j <arr.length ; j++) {
if( j%2 ==0 ){
System.out.print("~ ");
}else
System.out.print(arr[j]+" ");
}
}