简体   繁体   English

如何使用java将每个句子中的第一个字母大写后?

[英]how to capitalize first letter after period in each sentence using java?

I'm currently learning on how to manipulate strings and i think it'll take awhile for me to get used to it. 我目前正在学习如何操作字符串,我认为我需要一段时间才能习惯它。 I wanted to know how to capitalize a letter after a period in each sentence. 我想知道如何在每个句子中经过一段时间后将一封信用于大写。

The output is like this: 输出是这样的:

Enter sentences: i am happy. 输入句子:我很开心。 this is genius. 这是天才。

Capitalized: I am happy. 资本化:我很高兴。 This is genius. 这是天才。

I have tried creating my own code but its not working, feel free to correct and change it. 我已经尝试创建自己的代码,但它不工作,随时纠正和更改它。 Here is my code: 这是我的代码:

package Test;

import java.util.Scanner;

public class TestMain {
    public static void main(String[]args) {
        String sentence = getSentence();
        int position = sentence.indexOf(".");

        while (position != -1) {
            position = sentence.indexOf(".", position + 1);
            sentence = Character.toUpperCase(sentence.charAt(position)) + sentence.substring(position + 1);
            System.out.println("Capitalized: " + sentence);
        }

    }

    public static String getSentence() {
        Scanner hold = new Scanner(System.in);
        String sent;
        System.out.print("Enter sentences:");
        sent = hold.nextLine();
        return sent;
    }
}

The tricky part is how am i gonna capitalize a letter after the period(".")? 棘手的部分是如何在句号之后(“。”)将一封信写入资本? I don't have a lot of string manipulation knowledge so I'm really stuck in this area. 我没有很多字符串操作知识,所以我真的陷入了这个领域。

Try this: 尝试这个:

package Test;
import java.util.Scanner;

public class TestMain {
    public static void main(String[]args){

        String sentence = getSentence();
        StringBuilder result = new StringBuilder(sentence.length());
        //First one is capital!
        boolean capitalize = true;

        //Go through all the characters in the sentence.
        for(int i = 0; i < sentence.length(); i++) {
            //Get current char
            char c = sentence.charAt(i);

            //If it's period then set next one to capital
            if(c == '.') {
                capitalize = true;
            }
            //If it's alphabetic character...
            else if(capitalize && Character.isAlphabetic(c)) {
                //...we turn it to uppercase
                c = Character.toUpperCase(c);
                //Don't capitalize next characters
                capitalize = false;
            }

            //Accumulate in result
            result.append(c);
        }
        System.out.println(result);
    }

    public static String getSentence(){
        Scanner hold = new Scanner(System.in);
        String sent;
        System.out.print("Enter sentences:");
        sent = hold.nextLine();
        return sent;
    }
}

What this is doing it advancing sequentially through all of the characters in the string and keeping state of when the next character needs to be capitalized. 这是通过字符串中的所有字符顺序前进并保持下一个字符需要大写的状态。

在此输入图像描述

Follow the comments for a deeper exaplanations. 按照评论进行更深入的解释。

You could implement a state machine: 你可以实现一个状态机:

状态机

It starts in the capitalize state, as each character is read it emits it and then decides what state to go to next. 它从大写状态开始,当每个字符被读取时它会发出它,然后决定下一个要进入的状态。

As there are just two states, the state can be stored in a boolean. 由于只有两种状态,因此状态可以存储在布尔值中。

public static String capitalizeSentence(String sentence) {
    StringBuilder result = new StringBuilder();
    boolean capitalize = true; //state
    for(char c : sentence.toCharArray()) {    
        if (capitalize) {
           //this is the capitalize state
           result.append(Character.toUpperCase(c));
           if (!Character.isWhitespace(c) && c != '.') {
             capitalize = false; //change state
           }
        } else {
           //this is the don't capitalize state
           result.append(c);
           if (c == '.') {
             capitalize = true; //change state
           }
        }
    }
    return result.toString();
}
  1. Seems like your prof is repeating his assignments. 好像你的教授正在重复他的作业。 This has already been asked: Capitalize first word of a sentence in a string with multiple sentences 这已经被问到: 将一个句子中的第一个单词用多个句子大写

  2. Use a pre-existing lib: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalize(java.lang.String,%20char...) 使用预先存在的lib: http//commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#capitalize(java.lang.String,%20char。 ..)

and guava 和番石榴

    public static void main(String[] args) {
        String sentences = "i am happy. this is genius.";

        Iterable<String> strings = Splitter.on('.').split(sentences);

        List<String> capStrings = FluentIterable.from(strings)
                                  .transform(new Function<String, String>()
                                  {
                                    @Override
                                    public String apply(String input){
                                        return WordUtils.capitalize(input);
                                    }
                                 }).toList();

        System.out.println(Joiner.on('.').join(capStrings));
    }

You can use below code to capitalize first letter after period in each sentence. 您可以使用以下代码将每个句子中的第一个字母大写。

    String input = "i am happy. this is genius.";
    String arr[] = input.split("\\.");
    for (int i = 0; i < arr.length; i++) {

   System.out.print(Character.toUpperCase(arr[i].trim().
   charAt(0)) + arr[i].trim().substring(1) + ". ");
    }

I'd go for regex as it is fast to use: Split your string by ".": 我会使用正则表达式,因为它使用起来很快:用“。”分割你的字符串:

String[] split = input.split("\\.");

Then capitalize the first letter of the resulting substrings and reunite to result string. 然后大写生成的子字符串的第一个字母并重新结合到结果字符串。 (Be careful for spaces between periods and letters, maybe split by "\\. "): (注意句点和字母之间的空格,可以用“\\。”分隔):

String result = "";
for (int i=0; i < split.length; i++) {
    result += Character.toUpperCase(split[i].trim());
}
System.out.println(result);

Should do it. 应该这样做。

Here is solution with regular expressions: 这是正则表达式的解决方案:

public static void main(String[]args) {

    String sentence = getSentence();

    Pattern pattern = Pattern.compile("^\\W*([a-zA-Z])|\\.\\W*([a-zA-Z])");
    Matcher matcher = pattern.matcher(sentence);
    StringBuffer stringBuffer = new StringBuffer("Capitalized: ");

    while (matcher.find()) {
        matcher.appendReplacement(stringBuffer, matcher.group(0).toUpperCase());
    }

    matcher.appendTail(stringBuffer);
    System.out.println(stringBuffer.toString());

}

The correct method to do it with core java using regex will be 使用正则表达式使用核心java执行此操作的正确方法将是

String sentence = "i am happy. this is genius.";
Pattern pattern = Pattern.compile("[^\\.]*\\.\\s*");
Matcher matcher = pattern.matcher(sentence);
String capitalized = "", match;
while(matcher.find()){
    match = matcher.group();
    capitalized += Character.toUpperCase(match.charAt(0)) + match.substring(1);
}
System.out.println(capitalized);

Try this: 尝试这个:
1. Capitalize the first letter. 1.将第一个字母大写。
2. If the character is '.' 2.如果角色是'。' set the flag true so that you can capitalize the next character. 将标志设置为true,以便您可以将下一个字符大写。

public static String capitalizeSentence(String str)
{
    if(str.length()>0)
    {
        char arr[] = str.toCharArray();
        boolean flag = true;
        for (int i = 0; i < str.length(); i++)
        {
            if (flag)
            {
                if (arr[i] >= 97 && arr[i] <= 122)
                {
                    arr[i] = (char) (arr[i] - 32);
                    flag = false;
                }
            } else
            {
                if (arr[i] == '.')
                    flag = true;
            }
        }
        return new String(arr);
    }
    return str;
}

只是用

org.apache.commons.lang3.text.WordUtils.capitalizeFully(sentence);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM