How to capitalize the first letter of a string in a sentence? - java

I can't seem to find any solutions for this with just using String methods in Java. Having trouble trying to get the string out...
Heres my code:
import java.util.Scanner;
public class lab5_4
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s= scan.nextLine();
String s2 = s.toLowerCase();
for( int count = 0; count<= s2.length()-1; count++)
{
if( s2.charAt(count)==' ')
{
String s3 = s2.substring(count,count+1);
String s4= s3.toUpperCase();
System.out.print(s4);
}
}
}
}

The following method forces all characters in the input string into lower case (as described by the rules of the default Locale) unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.
public static String toDisplayCase(String s) {
final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
// to be capitalized
StringBuilder sb = new StringBuilder();
boolean capNext = true;
for (char c : s.toCharArray()) {
c = (capNext)
? Character.toUpperCase(c)
: Character.toLowerCase(c);
sb.append(c);
capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
}
return sb.toString();
}
TEST VALUES
a string
maRTin o'maLLEY
john wilkes-booth
YET ANOTHER STRING
OUTPUTS
A String
Martin O'Malley
John Wilkes-Booth
Yet Another String

You seem to be checking for a whitespace and then calling toUpperCase() on that. You want s3 to be the next character, so it should be String s3 = s2.substring(count+1, count+2);.
You are also only printing characters where the if is evaluated as true instead of all characters. You need the print statement to be outside the if. This will require more than basic changes, but this should get you started.

you can use pattern to select the first letter from each sentence
here an exemple
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s= scan.nextLine();
String toCappital = capitalTheFirstLetter(s);
System.out.println(toCappital);
}
public static String capitalTheFirstLetter(String sentence){
StringBuilder stringBuilder = new StringBuilder(sentence.toLowerCase());
Pattern pattern = Pattern.compile("\\s?([a-z])[a-z]*"); // ([a-z]) to group the first letter
Matcher matcher = pattern.matcher(sentence.toLowerCase());
while (matcher.find()) {
String fistLetterToCapital = matcher.group(1).toUpperCase();
stringBuilder.replace(matcher.start(1), matcher.end(1), fistLetterToCapital); // replace the letter with it capital
}
return stringBuilder.toString();
}
}
the output
Enter a sentence
how to capitalize the first letter of a string in a sentence ?
How To Capitalize The First Letter Of A String In A Sentence ?

Related

Taking first uppercase character of a multiple splitted string

So I want to print out the first uppercase character when splitting my String when it reaches a special character.
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if(input.contains("-")){
for (int i = 0; i < input.length(); i++){
String[] parts = input.split("-",2);
String string1 = parts[0];
String string2 = parts[1];
System.out.print(string1.substring(0, 0) + string2.substring(0,0));
}
}
}
``
I'll give an example of what I'd like it to do.
> input: Please-WooRk-siR
> output: PW
> input: This-Is-A-Test
> output: TIAT
So only print the first uppercase character of each substring.
Any ideas? Thanks in advance :)
If you use regular expressions, you can use a zero-width negative lookahead to remove all characters that aren't capitals at the starts of words:
public static String capitalFirstLetters(String s) {
return s.replaceAll("(?!\\b[A-Z]).", "");
}
When you run the test cases:
public static void main(String[] args) throws Exception {
System.out.println(capitalFirstLetters("Please-WooRk-siR"));
System.out.println(capitalFirstLetters("This-Is-A-Test"));
}
It prints:
PW
TIAT
This is one way to do it.
String str = "This-Is-a-Test-of-The-Problem";
StringBuilder sb = new StringBuilder();
for (String s : str.split("-")) {
char c = s.charAt(0);
if (Character.isUpperCase(c)) {
sb.append(c);
}
}
System.out.println(sb.toString());
Update the code to this :
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.contains("-")) {
String[] parts = input.split("-");
for (String part: parts) {
System.out.print(Character.isUpperCase(part.charAt(0)) ? part.charAt(0) : "");
}
}
}
}
Output :
1.
Input : A-Ba
AB
2.
Input : A-aB
A
3.
Input : A
Now, your test case :
Input : This-Is-A-Test
TIAT
Another solution by utilizing javas streaming API
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
if (input.contains("-")) {
List<String> collect =
Stream.of(input.split("-")) // get a stream of words
.map(word -> word.substring(0, 1)) // get first character only
.filter(character -> character.toUpperCase().equals(character)) // only keep if character is uppercase
.peek(System.out::print) // print out character
.collect(Collectors.toList()); // just needed for stream to start
}
}

with help of only charAt() and isSpaceChar() make first latter uppercase in java

I want to use only charAt() and toUpperCase() function and capitalize the first letter of each word in a sentence.
Like make the letter capital, that is just after the space.
I tried with this following code.
import java.util.Scanner;
class firstscap
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a sentence");
String s=sc.nextLine();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(Character.isSpaceChar(c))
{
char ch=s.charAt(++i);
ch=ch.toUpperCase();
}
}
System.out.println(s);
}
}
Several problems here.
s.charAt(n) gives you the n-th character of the String, not a pointer to the n-th character of the String. Changing that character does nothing to the String.
Also Strings are not mutable, which means you have no way to change them.
You can start build a new String from parts of the old String plus the Chars you have made uppercase.
You are capitalizing the characters but not storing them anywhere. I recommend you append all the characters to a StringBuilder*.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim(); // Input & omit leading/trailing whitespaces
StringBuilder sb = new StringBuilder();
// Append the first character, capitalized
if (s.length() >= 1) {
sb.append(Character.toUpperCase(s.charAt(0)));
}
// Start with character at index 1
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isSpaceChar(c)) {
sb.append(c).append(Character.toUpperCase(s.charAt(++i)));
} else {
sb.append(c);
}
}
s = sb.toString();
System.out.println(s);
}
}
A sample run:
Enter a sentence: hello world how are you?
Hello World How Are You?
* You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
Strings are immutable, you can't modify them.
Consider building a new String for the result e.g by using StringBuilder.
In the following example, a boolean flag is used to know if the last character was a space .
Also we check if the current character is a letter before putting it to upper case, otherwise it makes no sense.
This will also prevent possible crashes if the line ends with a space (since index charAt(i+1) would crash):
public static void main(final String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a sentence");
String s = sc.nextLine();
boolean wasSpace = false;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
if (wasSpace && Character.isLetter(c)) {
resultBuilder.append(Character.toUpperCase(c));
} else {
resultBuilder.append(c);
}
wasSpace = Character.isSpaceChar(c);
}
System.out.println(resultBuilder.toString());
}
Note :
If you also want the first letter of the whole sentence to be capitalized, just initialize wasSpace to true .
import java.util.Scanner;
public class A {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the string: ");
String a1 = (obj.nextLine()).trim();
String s1 = "";
char c2;
char arr[] = a1.toCharArray();
for (int i = 0; i <= a1.length() - 1; i++) {
if (Character.isSpaceChar(arr[i]) == true) {
++i;
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + " " + c2;
} else {
if (i == 0) {
c2 = Character.toUpperCase(a1.charAt(i));
s1 = s1 + "" + c2;
} else {
s1 = s1 + arr[i];
}
}
}
System.out.println(s1);
}
}

Given a string,s ,split the string into tokens

I define a token to be one or more consecutive English alphabetic letters. Then, print the number of tokens, followed by each token on a new line.String 's' is composed of English alphabetic letters, blank spaces, and any of the following characters: !,?._'#
Here what I'm doing.
import java.io.*;
import java.util.*;
public class apples {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
scan.close();
String[] splitString = (s.split("[\\s!,?._'#]+"));
System.out.println(splitString.length);
for (String string : splitString) {
System.out.println(string);
}
}
}
When I input a string starting with any of those above characters then my code is counting the character and while printing it gives a empty space, like this.
#dsd sd.sf
4
dsd
sd
sf
What I'm expecting is this.
#dsd sd.sf
3
dsd
sd
sf
Please Help!!
There is no text before the first separator so you get an empty string. I suggest you ignore the first empty string. You could also add a separator at the start so you know there is one you can always ignore. e.g.
String[] split = ("#"+s).split("\\W+");
int words = split.length - 1;
or you can truncate leading non letters
String[] split = s.replaceAll("^\\W+", "").split("\\W+");
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if (!scan.hasNext())
{
System.out.println(0);
}
else
{
String s = scan.nextLine();
scan.close();
s=s.replaceAll("^\\W+", "");
String[] words = s.split("[\\s',!?._#]+");
int len=words.length;
System.out.println(len);
for(String i:words)
{
System.out.println(i);
}
}
}
}

How do I make a new String based on another string's unknown length?

I am currently in a computer programming class and at a dead end for "creating a template" for this 2-person hang man game.
First, person#1 is prompted for a phrase (contains all lowercase)
Then, I must take whatever phrase they choose and turn it into a template with all ?'s.
Then, as person#2 guesses letters, I must "reveal" the phrase and have the ?'s turn into the phrase letters.
I can't get past turning it into the template though. An example is:
person#1's phrase: "hello world"
desired template outcome: "????? ?????"
This is what I have so far... I'm having trouble at public static String createTemplate(String sPhrase)
import java.util.Scanner;
public class Program9
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
Scanner stdIn = new Scanner (System.in);
int cnt = 0; //counter is set to zero
String sPhrase;
boolean def;
System.out.print("Enter a phrase consisting of only lowercase letters and spaces: ");
sPhrase = scanner.nextLine(); //reads into variable set to Scanner.nextLine()
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String template = createTemplate(sPhrase); //will run through "createTemplate" and show whatever on there.
do
{
char guess = getGuess(stdIn); //will run through "getGuess" and show whatever SOP and return from that. WORKS.
cnt = cnt + 1; //counts the guess
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String updated = updateTemplate(template, sPhrase, guess); //runs throuhgh and prints updated template
} while (!exposedTemplate(sPhrase)); //will loop back if updated template still has ?'s
System.out.println("Good job! It took you " + cnt + " guesses!");
}
public static String createTemplate(String sPhrase)
{
String template = null;
String str;
sPhrase.substring(0, sPhrase.length()+1); //not sure if +1 needed.
sPhrase.equals(template);
//THIS IS WHERE IM HAVING PROBLEMS
}
public static char getGuess(Scanner stdIn)
{
//repeatedly prompts user for char response in range of 'a' to 'z'
String guess;
do
{
System.out.print("Enter a lowercase letter guess : ");
guess = stdIn.next();
} while (Character.isDigit(guess.charAt(0)));
char firstLetter = guess.charAt(0);
return firstLetter;
}
public static String changeCharAt(String str, int ind, char newChar)
{
return str.substring(0, ind) + newChar + str.substring(ind+1);
//freebie: returns copy of str with chars replaced
}
public static String updateTemplate(String template, String sPhrase, char guess)
{
//will have to include changeCharAt
}
public static boolean exposedTemplate(String template)
{
// returns true exactly when there are no more ?'s
}
}
A simple solution would be:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll("[a-zA-Z]", "?");
}
the replaceAll method of the String class in Java replaces all parts of the string that match the supplied regular expression with a string (in this case ?)
Learning regular expressions (known as regexes) may not be in the scope of this assignment, but is a very useful skill for all computer programmers. In this example I've used the regular expression [a-zA-Z] which means replace any upper or lower case character, however you could also use a character class like \\w.
There is an excellent tutorial on Java regexes here: https://docs.oracle.com/javase/tutorial/essential/regex/
You'll need a for-loop, you'll need to check each character of the phrase, String#charAt should help. If the character is not a space, you would append an ? to the template, otherwise you'll need to append a space...
See The for Statement for more details...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (int index = 0; index < sPhrase.length(); index++) {
if (sPhrase.charAt(index) != ' ') {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
Equally you could use...
StringBuilder sb = new StringBuilder(sPhrase.length());
for (char c : sPhrase.toCharArray()) {
if (c != ' ')) {
sb.append("?");
} else {
sb.append(" ");
}
}
sTemplate = sb.toString();
But I thought the first one would be easier to understand...
Just use a regex and String.replaceAll() method:
public static String createTemplate(String sPhrase)
{
return sPhrase.replaceAll(".", "?");
}
In this example, the first parameter is a regex, so "." matches all characters. The second parameter is the string to replace all regex matches with, a "?".

What's wrong with my Java code? It should count the spaces, but returns 0

The code is copied below. It should return the number of spaces if the character variable l is equal to a space, but always returns a 0.
I've tested it with letters and it worked, for example if I'm asking it to increment when the variable l is equal to e and enter a sentence with e in, it will count it. But for some reason, not spaces.
import java.util.Scanner;
public class countspace {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = input.next();
System.out.println(wc(str));
}
public static int wc(String sentence) {
int c = 0;
for (int i = 0; i < sentence.length(); i++) {
char l = sentence.charAt(i);
if (l == ' ') {
c++;
}
}
return c;
}
}
Scanner.next() (with the default delimited) is only parsing as far as the first space - so str is only the first word of the sentence.
From the docs for Scanner:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Use nextLine instead. You can also print the line for debugging:
System.out.println(str);
Use String str = input.nextLine(); instead of String str = input.next();
This is the way you should do to get the next string.
You could have checked that str has the wrong value.

Categories