java - 检查字符中的下一个字母何时在句点之后

标签 java arrays char

所以我正在编写一个练习程序,但我有点卡住了。我想检查 char[] 数组中的第一个字符是否是字母,我尝试过 isLetter,但显然你不能在 char 中执行此操作。

例句:“/我的名字是克里斯” 注意开头的:“/”。

我想让第一个字母大写。所以它会是

固定例句:“/我的名字是克里斯”

我的代码很可能会非常困惑和过度编码,但我还没有到可以缩短它的程度,我还没有那么先进。就像我说的,它很可能会很困惑。

代码如下:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
import java.util.StringTokenizer;


public class FileOrUserSentenceHandler 
{
Scanner keyboard = new Scanner(System.in);
String userChoice, fileName;
char period = '.';
String s;
String userSentence;




public String getUserChoice()
{

    System.out.println("Would you like the program to read from a file or a sentence from you? Type 'File' for it to read an already-created file, Type 'me' for it to read a sentence from you.");
    userChoice = keyboard.nextLine();

    return userChoice;
}

public void decideChoice() throws Exception
{
    if(userChoice.equalsIgnoreCase("file"))
    {
        pickedFile();
    }
    else if(userChoice.equalsIgnoreCase("me"))
    {
        pickedMe();
    }
    else
    {
        getUserChoice();
        decideChoice();
    }
}

public void pickedFile() throws Exception
{

    //create file object
    File outFile = new File("CreatedFile.txt");
    BufferedWriter outBWriter = new BufferedWriter(new FileWriter(outFile));

    outBWriter.write("you picked the file option. why not pick the 'me' option?");

    //close the file
    outBWriter.close();
    System.out.println("File was created, Data was written to file.");


    try
    {
        File inFile = new File("CreatedFile.txt");

        BufferedReader inBReader =  new BufferedReader(new FileReader(inFile));

        do
        {
            s = inBReader.readLine();
            if(s == null)
            {
                break;
            }

            System.out.println(s);

            System.out.println("Fixing the sentence from the file...");
            Thread.sleep(3000);

            char[] charArray = s.toCharArray();


            for(int i = 0; i < charArray.length; i++)
            {

                if(i == 0)
                {
                    charArray[i] = Character.toUpperCase(charArray[i]);
                }

                if(charArray[i] == '.')
                {
                    charArray[i + 2] = Character.toUpperCase(charArray[i + 2]);
                }
            }

            System.out.println(charArray);

        }while(s != null);
    }
    catch(Exception e)
    {
        System.out.println("Error. Closing program...");
        System.exit(0);
    }


}

public void pickedMe()
{
    System.out.println("You picked the 'me' option. Please enter a sentence below:");
    userSentence = keyboard.nextLine();

    StringTokenizer userSentenceEdited = new StringTokenizer(userSentence, " "); //creates a tokenized String of userSentence, checks the spaces
    StringBuffer sb = new StringBuffer();

    while(userSentenceEdited.hasMoreElements())
    {
        sb.append(userSentenceEdited.nextElement()).append(" ");
    }

    userSentence = sb.toString();

    //System.out.println(userSentence); // printed out to check if it was working properly

    outerloop : if((userSentence.charAt(userSentence.length() - 1) != '.'))
    {
            if(userSentence.charAt(userSentence.length() - 1) == ' ')
            {
                userSentence = userSentence.trim();
            }

            if(userSentence.charAt(userSentence.length() - 1) == '.')
            {
                //System.out.println("hello");
                break outerloop;
            }

        userSentence += '.';
    }

    //System.out.println(sb.toString().trim());


    char[] userCharArray = userSentence.toCharArray(); //converts the userSentence to a char[] array

    for(int i = 0; i < userCharArray.length; i++)
    {
        if(i == 0) //checks if it's at the beginning of the array, if so, capitalizes it.
        {
            userCharArray[i] = Character.toUpperCase(userCharArray[i]);
        }

        if(i == '.') //checks if it's at a period, if so, it checks if it's at the end of the sentence
                                    //if it is, it breaks out of the loop, which means it doesn't capitalize nothing,
                                    //if it's not the end of the String, it capitalizes 2 spaces over.
        {
            if(i == userCharArray.length)
            {
                break;
            }
            userCharArray[i + 2] = Character.toUpperCase(userCharArray[i + 2]);
        }

    }

    System.out.println(userCharArray);
}


}

再说一遍,我知道这很可能非常困惑,这一点怎么强调都不过分,我稍后会处理它。

请客气一点,这是我的第一个“大”计划。

最佳答案

你可以这样做...

 if (Character.isLetter(str.charAt(0))){
     //change the first char to upper case
     str = str.substring(0,1).toUpperCase() + str.substring(1);
 }

其中 str 是您正在使用的字符串的变量名称

这里是另一种修复字符串的方法,而不是遍历整个字符串并始终检查下一个字母出现在句点之后的位置(因为它可能会在句点之后出现任意数量的空格),而是另一种修复字符串的方法,以便句点之后的字母始终大写。

//split all sentences and put them into an array
String[] tokens = str.trim().split("\\.");
//initialize a result string
String resultString = " ";
//loop through every sentence capitalizing the first character.
for(int i = 0; i<tokens.length; i++){
   //first trim off any whitespace that may occur after period...
   tokens[i] = tokens[i].trim();
   //then capitalize the first letter of every sentence
   tokens[i] = tokens[i].substring(0,1).toUpperCase() + tokens[i].substring(1);
   //then add the sentence with the upperCase first character to your result string
   resultString += " " + tokens[i] + ".";
}
//once out of loop, resultString has the contents of all the sentences with a capital letter to begin the sentence. Notice I use str for my string name, you use s

关于java - 检查字符中的下一个字母何时在句点之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645443/

相关文章:

java - 如何在低优先级的 Android/Java 上执行 Linux 命令?

java - 如何在 libgdx 2d 粒子编辑器中为 Sprite 模式动画设置动画速度?

php - 如何从 PayPal SDK 访问交易数据?

c++ - 从字符串中删除重复的字符

java - 如何在 docker-ubuntu 环境中设置 JAVA_HOME?

java - 检查扫描仪输入是否有 "$"字符

c - 根据长度崩溃对静态数组中的字符串进行排序? |错误分配/访问|

c++ - 如何将数组保存到两个类方法中?

c - 输入用户的密码并检查它是否包含字符、字母和数字

c - 在 while 循环中扫描字符