【发布时间】:2016-04-15 00:49:33
【问题描述】:
我已经写了大部分内容。我只是不知道如何将每行的第一个字母大写。问题是:
编写一个程序来检查文本文件的几种格式和标点符号问题。该程序要求输入文件和输出文件的名称。然后它将所有文本从输入文件复制到输出文件,但有以下两个变化: (1) 任何两个或多个空白字符的字符串都被单个空白替换; (2) 所有句子都以大写字母开头。第一个句子之后的所有句子都以句点、问号或感叹号开头,后跟一个或多个空格字符。
我已经编写了大部分代码。我只需要帮助每个句子的第一个字母大写。这是我的代码:
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
inputSent = inputStream.readLine();
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
//Find a way to make the first letter capitalized
while(inputSent != null)
{
outputStream.println(inputSent);
System.out.println(inputSent);
inputSent = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
}
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String inputName;
String result;
String sentence;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of your input file: ");
inputName = keyboard.nextLine();
File input = new File(inputName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(input);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error opening the file. Goodbye!" + input);
System.exit(0);
}
System.out.println("Enter a line of text:");
sentence = keyboard.nextLine();
outputStream.println(sentence);
outputStream.close();
System.out.println("This line was written to:" + " " + input);
System.out.println("\n");
}
}
【问题讨论】:
-
您可以创建一个“特殊字符”数组,仅在句子末尾使用,然后如果您看到这个字符,您就知道一个新句子正在开始。检查下一个字符(不是空格)是否大写。
-
您知道句子从输入的开头或标点符号(!、? 或 .)之后开始。因此,在它们之后查找第一个非空白字符并将其大写。为此,您可以使用正则表达式、
indexOf()或split()。