简体   繁体   中英

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...)

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

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.
2. If the character is '.' set the flag true so that you can capitalize the next character.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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