4

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.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Pearl
  • 123
  • 1
  • 7
  • 3
    @Rekin:- Even if it is a homework, OP has presented his/her attempt. So it is a legitimate question :) – Rahul Tripathi Aug 27 '15 at 12:46
  • Just walk through your code line-by-line, checking what each assignment will do - you should be able to find the problem(s) easy enough by doing this. You could do this by hand, by debugging or by adding debug statements to your code. – Bernhard Barker Aug 27 '15 at 12:48
  • [Character.toUpperCase()](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toUpperCase%28char%29) is the method from the _string manipulation knowledge_ that you may be missing. For the rest of the code, the general code-writing knowledge is all that is needed. – Dragan Bozanovic Aug 27 '15 at 12:49
  • @RahulTripathi But the problem with said code wasn't described in sufficient detail ("it's not working" is not exactly helpful). – Bernhard Barker Aug 27 '15 at 12:51
  • @Dukeling:- Indeed, but in that case *What is meant by it's not working? or Provide more details* would have been an idle comment rather than asking if its homework. Isn't it? :) – Rahul Tripathi Aug 27 '15 at 12:54
  • Regular expression (regex) is also part of string manipulation. Are you willing to use it in your solution? – Pshemo Aug 27 '15 at 12:54
  • @RahulTripathi Yes, whether it's homework is largely irrelevant (at least in my opinion). I was just challenging the claimed legitimacy of the question. – Bernhard Barker Aug 27 '15 at 13:00
  • What kind of sentences you want to handle? Is sentence like `i live in u.s.a. but i am going to move to canada.` possible? Also what about quotes like `sentece one. "sentence two".` – Pshemo Aug 27 '15 at 13:01
  • its not working. it gave me a StringIndexOutOfBoundsException error. By the way, this is not a homework. – Pearl Aug 27 '15 at 13:15

9 Answers9

5

You could implement a state machine:

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();
}
weston
  • 54,145
  • 21
  • 145
  • 203
  • If you only exit capitalize state when it's an alphabetical character, then that's exactly what I implemented I think :-) – Alfonso Presa Aug 27 '15 at 13:02
  • Well I've gone for Non-whitespace, non-period. Both satisfy their requirements. – weston Aug 27 '15 at 13:05
  • Don't use `result += Character.toUpperCase(c);` in a loop. Use `StringBuilder` and its `append` method. – Pshemo Aug 27 '15 at 13:10
  • Yeah I know, just not trying to teach so many concepts at once. Code didn't actually work, which is bigger concern, does now though. – weston Aug 27 '15 at 13:23
4

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.

enter image description here

Follow the comments for a deeper exaplanations.

Alfonso Presa
  • 1,024
  • 7
  • 11
1

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

}
1
  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));
    }
Community
  • 1
  • 1
Somaiah Kumbera
  • 7,063
  • 4
  • 43
  • 44
1

Just use

org.apache.commons.lang3.text.WordUtils.capitalizeFully(sentence);
Gabriel Pereira
  • 580
  • 5
  • 9
0

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) + ". ");
    }
Rafiq
  • 740
  • 1
  • 5
  • 17
0

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.

Niklas
  • 375
  • 1
  • 3
  • 17
-1

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);
afzalex
  • 8,598
  • 2
  • 34
  • 61
-1

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;
}
anirban.at.web
  • 349
  • 2
  • 11