1、给定一个字符串数组{“nba”,“abc”,“cba”,“zz”,“qq”,“haha”},请按照字典顺序进行从小到大的排序。
2、请统计"nba"在字符串"nbaernbatynbauinbaopnba"中出现的次数
3、已知字符串:”this is a test of java”.
按要求执行以下操作:
(1) 统计该字符串中字母s出现的次数
(2) 取出子字符串”test”
(3) 将本字符串复制到一个字符数组Char[] str中.
(4) 将字符串中每个单词的第一个字母变成大写, 输出到控制台。
(5) 用两种方式实现该字符串的倒叙输出。(用StringBuffer和for循环方式分别实现)
(6) 将本字符串转换成一个字符串数组,要求每个数组元素都是一个有意义的额英文单词,并输出到控制台
4、从键盘输入一个字符串
编写一个程序,判断输出一个字符串中大写英文字母数,和小写英文字母数,和其他非英文字母数
import java.util.Arrays;
import java.util.Scanner;
public class HomeWork {
/*1、给定一个字符串数组{"nba","abc","cba","zz","qq","haha"},
请按照字典顺序进行从小到大的排序。*/
public static void main(String[] args) {
// test1();
// test2();
// test3();
test4();
}
private static void test4() {
Scanner sc=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String a=sc.nextLine();
int numUppercase = 0;// 大写英文字母数
int numlowercase = 0;// 小写英文字母数
int numOther = 0;// 其他非英文字母数
for (int i = 0; i < a.length(); i++) {
char c = a.charAt(i);//把每个元素摘出来
if (c >= 'a' && c <= 'z') {
numlowercase++;
} else if (c >= 'A' && c <= 'Z') {
numUppercase++;
} else {
numOther++;
}
}
System.out.println("大写英文字母数:" + numUppercase + "小写英文字母数:" + numlowercase + "非英文字母数:" + numOther);
sc.close();
}
private static void test3() {
String a="this is a test of java";
String b="s";
String c="test";
int index=0;
int count=0;
//统计该字符串中字母s出现的次数
while((index=a.indexOf(b, index))!=-1){
index+=b.length();
count++;
}
System.out.println("字符串中字母出现的次数:"+count);
// 取出子字符串”test”
if(a.contains(c)){
System.out.println(a.substring(a.indexOf(c), a.indexOf(c)+c.length()));
}
// 将本字符串复制到一个字符数组Char[] str中.
char[] str=a.toCharArray();
System.out.println(str);
// 将字符串中每个单词的第一个字母变成大写, 输出到控制台。
String[] split=a.split(" ");
for (int i = 0; i < split.length; i++) {
// .substring(0,1) 截取数组的首字母 +split[i].substring(1); 再加上后面
String sp2 = split[i].substring(0, 1).toUpperCase() + split[i].substring(1);
System.out.print(sp2 + " ");
}
/* 用两种方式实现该字符串的倒叙输出。
(用StringBuffer和for循环方式分别实现) */
//方法一
System.out.println();
char[] char1=a.toCharArray();
for (int i = char1.length-1 ; i>=0; i--) {
System.out.print(char1[i]);
}
//方法二
System.out.println();
StringBuffer sb=new StringBuffer(a);
System.out.println(sb.reverse());
/*将本字符串转换成一个字符串数组,
要求每个数组元素都是一个有意义的额英文单词,并输出到控制台*/
System.out.println();
String[] sp=a.split(" ");
for(int i=0;i<sp.length;i++){
System.out.print(sp[i]+",");
}
}
/*1、给定一个字符串数组{"nba","abc","cba","zz","qq","haha"},
请按照字典顺序进行从小到大的排序。*/
public static void test1(){
String[] a=new String[]{"nba","abc","cba","zz","qq","haha"};
for(int i=0;i<a.length-1;i++){
for(int j=0;j<a.length-1-i;j++){
if(a[j].compareToIgnoreCase(a[j+1])>0){
String temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println(Arrays.toString(a));
}
/* 请统计"nba"在字符串"nbaernbatynbauinbaopnba"中出现的次数*/
public static void test2(){
String a="nbaernbatynbauinbaopnba";
String b="nba";
int count=0;
int index=0;
while((index=a.indexOf(b,index))!=-1){
index+=b.length();
count++;
}
System.out.println(count);
}
}