從命令列引數中得到一個字串,統計該字串中字母 a 的出現次數。
阿新 • • 發佈:2020-12-31
- 從位元組或字串陣列中得到一個字串,統計該字串中字母 a 的出現次數。
public class Test2 {
public static void main(String[] args) {
// TODO 自動生成的方法存根
char e[]= {'h','o','a','s','a'};//位元組陣列
StringBuffer s1=new StringBuffer();
for(char k:e)
s1.append(k);
/*StringBuffer s1=new StringBuffer();
String e[]= {"heallao","may"};//字串陣列
for(String k:e)
s1.append(k);*/
String s=s1.toString();
int count=0;
for(int k=0;k<s.length();k++) {
if(s.charAt(k)=='a') {
count++;
}
}
System.out.println("字串"+s+"中a出現"+count+"次");
}
}
從鍵盤輸入若干行文字,最後輸入的一行為“ end "時 ,代表結束標記。
① 統計該段文字中英文字母的個數。
② 將其中的所有 the 全部改為 a ,輸出結果。
③ 將該文欄位所有的數字串找出來並輸出。
這裡第三小題輸出數字串用了兩種方法,第一種string拼接效率比StringBuffer類的拼接方法差,因為每次拼接都佔用新的記憶體,所以要習慣用StringBuffer。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test2 {
public static void main(String[] args) throws IOException{
// 使用readLine一定要捕獲IO異常
int yingWen= 0;
String shuZi="";
StringBuffer shuZi1=new StringBuffer();
StringBuffer re=new StringBuffer();
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String s=in.readLine();
while(!(s.equals("end"))) {
for(int k=0;k<s.length();k++) {
char c=s.charAt(k);
if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) {
yingWen++;
}
}
//a替代the
re.append(s.replaceAll("the", "a"));
//String字串拼接
for(int k=0;k<s.length();k++) {
char c=s.charAt(k);
if(c>='0'&&c<='9') {
shuZi=shuZi+c;
}
else {
shuZi=shuZi+" ";
}
}
//StringBuffer物件拼接
boolean before=false;//判斷前一個字元是不是數字
for(int k=0;k<s.length();k++) {
char c=s.charAt(k);
if(c>='0'&&c<='9') {
if(!before) {
before=true;
}
shuZi1.append(c);
}
else {
if(before) {
before=false;
shuZi1.append("\t");
}
}
}
//讀取下一行
s=in.readLine();
}
System.out.println("英文數:"+yingWen);
System.out.println("'a'替代'the':"+re.toString());
System.out.println("數字串"+shuZi);
System.out.println("StringBuffer數字串"+shuZi1.toString());
}
}