Java文件操作

傻熙Ta爸 2011-05-13 10:40:22
(1)计算这篇短文的字符数(含空白)共有多少?
(2)若不含空白,这篇短文共有多少个字符?
(3)统计这篇短文用了多少个单词“to”。
(4)将这篇短文内所有大写字母改成小写,并将更改后的短文写到文本文件”joke.txt” 里。
There was an American couple who had no children, so they wanted to adopt a child. Finally, an orphanage contacted them, saying, "We have a baby for adoption.It's a Russian orphan." The couple was delighted and went to bring the baby home.
On the way home, they stopped by a university to enroll in a Russian course. "Why do you want to learn Russian? The English that we speak is a very good language," the university secretary asked."Well, we just adopted a Russian baby. When he begins to speak Russian in a few years, we are afraid that we might not be able to understand him," the couple replied.

...全文
284 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
3楼正解!
ydh85362600 2011-05-14
  • 打赏
  • 举报
回复

1.首先算出短文的字符,接住用.trim()得到新的字符串 ~前减后。得到空白
2.1中有了
3.简单的算法
4.。。。。。
不知道行不行呢
茫茫大海 2011-05-13
  • 打赏
  • 举报
回复

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;


public class T {
public static void main(String[] args) throws IOException {
//读入文件
FileInputStream fis = new FileInputStream(new File("data.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuffer sb = new StringBuffer();
String str = br.readLine();
while(str != null) {
sb.append(str);
str = br.readLine();
}
br.close();

//统计文件的字符数、非空白字符数和单词to的个数
str = sb.toString();
int count = str.length();//总共的字符数
String[] words = str.split(" ");
int count1 = 0;//非空白字符数
int count2 = 0;//to的个数
for(String word : words) {
count1 += word.length();
if(word.equals("to")) {
count2 ++;
}
}

System.out.println("文件中总共有" + count + "个字符!");
System.out.println("文件中总共有" + count1 + "个非空白字符!");
System.out.println("文件中总共有" + count2 + "个单词to!");
//文件中的所有大写字母改成小写字母
str = str.toLowerCase();

//转换后的内容写入文件
FileOutputStream fos = new FileOutputStream("joke.txt");
fos.write(str.getBytes());
fos.close();
}
}

凉岑玉 2011-05-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wklken 的回复:]
读入文件,组成一个字符串str
字符串长度:str.length()
String[] arr = str.split(" ")
for循环遍历arr
可以统计非空白字符数及有多少个to

最后toUpperCase()转,输出
[/Quote]
just do it!
wklken 2011-05-13
  • 打赏
  • 举报
回复
读入文件,组成一个字符串str
字符串长度:str.length()
String[] arr = str.split(" ")
for循环遍历arr
可以统计非空白字符数及有多少个to

最后toUpperCase()转,输出

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧