【问题标题】:How to capitalize first letter in this program如何在这个程序中大写第一个字母
【发布时间】: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()

标签: java string


【解决方案1】:

由于您的代码已经包含inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);,我假设inputSent 可以包含多个句子,或者可能只表示文件的一行和部分句子。

因此,我建议您首先将整个文件读入一个字符串(如果它不是太大),然后在该字符串上使用split() 将其分成单独的句子,将第一个字符大写并再次加入它们。

例子:

String[] sentences = fileContent.split("(?<=[?!.])\\s*");
StringBuilder result = new StringBuilder();
for( String sentence : sentences) {
  //append the first character as upper case
  result.append( Character.toUpperCase( sentence.charAt(0) ) );
  //add the rest of the sentence
  result.append( sentence.substring(1) );
  //add a newline
  result.append("\n");
}

//I'd not replace the input, but to be consistent with your code
fileContent = result.toString();

【讨论】:

    【解决方案2】:

    最简单的方法可能是使用来自 Apache commons-langs 的 WordUtil

    您应该使用capitalise 方法和分隔符作为参数。

    【讨论】:

    • 该确切行已包含在问题中。除此之外,代码暗示字符串中有多个句子,而您发布的行只会处理第一个。
    • @Thomas 你是对的!我会修改我的答案。为你 +1
    【解决方案3】:

    你可以试试下面的正则表达式:

    (\S)([^.!?]*[.!?]( |$))
    

    • 代码:

      public static void main(String[] args) {
          String inputSent = "hi! how are you? fine, thanks.";
          inputSent = inputSent.replaceAll("\\s+", " ").trim();
          Matcher m = Pattern.compile("(\\S)([^.!?]*[.!?]( |$))").matcher(inputSent);
          StringBuffer sb = new StringBuffer();
          while (m.find()) {
              m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2) + "\n");
          }
          m.appendTail(sb);
          System.out.println(sb);
      }
      

      在线查看demo

    • 输出:

      Hi! 
      How are you? 
      Fine, thanks.
      

    【讨论】:

    • 我会描述正则表达式的各个部分以便更好地理解。除此之外,[^.!?]*[.!?] 可以使用不情愿的量词简化为 pt .*?[.!?]。此外,使用Matcher 也只需要找到句子中的第一个字符,因为appendReplacement() 也会在匹配之前附加部分。
    【解决方案4】:

    在 ASCII 表中,小写和大写只是彼此相距 32 个位置的整数...

    试试这样的:

    String inputSent = .... //where ever it does come from...
    System.out.println(inputSent.replace(inputSent.charAt(0), (char) (inputSent.charAt(0) - 32)));
    

    或使用某种 APACHE 库,例如 WordUtils

    【讨论】:

    • inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1); 行已经出现在此代码中,并且考虑了除 ASCII 字符之外的其他字符。问题是当同一行中有多个句子时。
    • Java 的 StringcharcharAt 不是 ASCII;它们是Unicode/UTF-16。
    【解决方案5】:

    我会将textFile() 更改为以下内容:

    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));
            while ((inputSent = inputStream.readLine()) != null) {
                char[] chars = inputSent.toCharArray();
                chars[0] = Character.toUpperCase(chars[0]);
                inputSent = new String(chars);
    
                inputSent = inputSent.replaceAll("\\s+", " ").trim();
                inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
    
                inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
                System.out.println("-> " + inputSent);
                outputStream.println(inputSent);
    
            }
            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);
        }
    }
    
    1. 这将逐行读取文本文件。
    2. 在第一个字符上
    3. 在 while 循环中执行此操作

    你原来的 textFile() 的问题是它只在它读取的第一行应用大写的第一个字符、空格等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 2013-09-01
      • 1970-01-01
      • 2018-07-08
      • 2023-03-15
      • 2022-01-18
      • 1970-01-01
      • 2022-09-30
      相关资源
      最近更新 更多