对一个文本中句子里的单词进行操作
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class lab4 {
public static boolean isCharVowel(char ch) {
return ch == 'a' || ch == 'e' || ch == 'u'
|| ch == 'i' || ch == 'o' || ch == 'y';
}
public static void main(String[] args) {
String path = "F:\\lab.txt";
File file = new File(path);
FileReader fr = null;
try {
fr = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
String line;
try {
while((line = br.readLine()) != null){
for (String str : line.split(" ")) {
char c = str.charAt(0);
String toPrint = str;
if (isCharVowel(c)) {
toPrint = String.valueOf(c).toUpperCase() +
str.substring(1);
}
System.out.print(toPrint + " ");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
将文本中每一句中的单词逆序排列(1.句子顺序不能改变 2.每个单词里字母的顺序不能改变)
先分割为每一句话,再根据空格分割后,倒叙输出
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
//读取文件内容
String path = "D:\\aa\\lab.txt";
File file = new File(path);
if (!file.exists()){
System.out.println("文件不存在!");
return;
}
InputStreamReader read = null;
BufferedReader bufferedReader=null;
StringBuffer sb=null;
try {
read = new InputStreamReader(new FileInputStream(file));
bufferedReader = new BufferedReader(read);
String lineText = null;
sb=new StringBuffer();
while((lineText = bufferedReader.readLine())!=null){
sb.append(lineText);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//分割每句话
String[] strs = sb.toString().split(",|\\.|\\!|\\?");
reverseTxt(strs);
System.out.println("逆序后的结果:");
for (String s:strs){
System.out.println(s);
}
}
public static void reverseTxt(String [] arr){
StringBuffer sb=null;
for(int i=0;i<arr.length;i++){
String[] s = arr[i].split(" ");
sb=new StringBuffer();
for(int j=s.length-1;j>=0;j--)
sb.append(s[j]+" ");
arr[i]=sb.toString().trim();
}
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!