- 从字节或字符串数组中得到一个字符串,统计该字符串中字母 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());
}
}