Convert String into Title Case - java

I am a beginner in Java trying to write a program to convert strings into title case. For example, if String s = "my name is milind", then the output should be "My Name Is Milind".
import java.util.*;
class TitleCase
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("ent");
String s=in.nextLine();
String str ="";
char a ;
for(int i =0;i<s.length()-1;i++)
{
a = s.charAt(i);
if(a==' ')
{
str = str+(Character.toUpperCase(s.charAt(i+1)));
}
else
{
str =str+(Character.toLowerCase(a));
}
}
//for(int i =0; i<s.length();i++)
//{
System.out.println(str);
//}
}
}

You are trying to capitalize every word of the input.
So you have to do following steps:
get the words separated
capitalize each word
put it all together
print it out
Example Code:
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("ent");
String s=in.nextLine();
//now your input string is storred inside s.
//next we have to separate the words.
//here i am using the split method (split on each space);
String[] words = s.split(" ");
//next step is to do the capitalizing for each word
//so use a loop to itarate through the array
for(int i = 0; i< words.length; i++){
//we will save the capitalized word in the same place again
//first, geht the character on first position
//(words[i].charAt(0))
//next, convert it to upercase (Character.toUppercase())
//then add the rest of the word (words[i].substring(1))
//and store the output back in the array (words[i] = ...)
words[i] = Character.toUpperCase(words[i].charAt(0)) +
[i].substring(1);
}
//now we have to make a string out of the array, for that we have to
// seprate the words with a space again
//you can do this in the same loop, when you are capitalizing the
// words!
String out = "";
for(int i = 0; i<words.length; i++){
//append each word to out
//and append a space after each word
out += words[i] + " ";
}
//print the result
System.out.println(out);
}

Using Java 8 streams:
String titleCase = (new ArrayList<>(Arrays.asList(inputString.toLowerCase().split(" "))))
.stream()
.map(word -> Character.toTitleCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));

The problem is with the way you're adding characters. Take a look at your if condition:
a = s.charAt(i);
if(a==' ')
{
// Here you are adding not the current character, but the NEXT character.
str = str+(Character.toUpperCase(s.charAt(i+1)));
}
else
{
// Here you are adding the current character.
str =str+(Character.toLowerCase(a));
}
As a result of this condition, you will skip a character if your input string contains a space, then repeat another character that you've already added.
Additionally, you're not looping through the whole string because your loop conditional goes to s.length()-1. Change that to just s.length(). However, if you do that, you may run into an exception if the input string ends with a space (since you'll try to check for a character at an out-of-bound index).
Here's what the fixed code would look like:
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("ent");
String s=in.nextLine();
String str ="";
char a ;
for(int i =0;i<s.length();i++)
{
a = s.charAt(i);
if(a==' ')
{
str = str+Character.toLowerCase(a)+(Character.toUpperCase(s.charAt(i+1)));
i++; // "skip" the next element since it is now already processed
}
else
{
str =str+(Character.toLowerCase(a));
}
}
System.out.println(str);
}
NOTE: I only fixed the code that you supplied. However, I'm not sure it works the way you want it to - the first character of the string will still be whatever case it started in. Your conditional only uppercases letters that are preceded by a space.

You want to change the case of the first letter of each word of a String.
To do so, I would follow the following steps :
split the String in words : see String.split(separator)
retrieve the first letter of each word : see String.charAt(index)
retrieve its capitalized version : the Character.toUpperCase(char) you use is perfect
concatenate the capitalized letter with the rest of the word : concatenation operator (+) and String.substring
create a new String from the capitalized words : see String.join(separator)

Code Golf variation... I challenge anyone to make it any simpler than this:
public String titleCase(String str) {
return Arrays
.stream(str.split(" "))
.map(String::toLowerCase)
.map(StringUtils::capitalize)
.collect(Collectors.joining(" "));
}

By the way: Unicode distinguishes between three cases: lower case, upper case and title case. Although it does not matter for English, there are other languages where the title case of a character does not match the upper case version. So you should use
Character.toTitleCase(ch)
instead of Character.toUpperCase(ch) for the first letter.
There are three character cases in Unicode: upper, lower, and title. Uppercase and lowercase are familiar to most people. Titlecase distinguishes characters that are made up of multiple components and are written differently when used in titles, where the first letter in a word is traditionally capitalized. For example, in the string "ljepotica",[2] the first letter is the lowercase letter lj(\u01C9 , a letter in the Extended Latin character set that is used in writing Croatian digraphs). If the word appeared in a book title, and you wanted the first letter of each word to be in uppercase, the correct process would be to use toTitleCase on the first letter of each word, giving you "Ljepotica" (using Lj, which is \u01C8). If you incorrectly used toUpperCase, you would get the erroneous string "LJepotica" (using LJ, which is \u01C7).
[The Java™ Programming Language, Fourth Edition, by James Gosling, Ken Arnold, David Holmes (Prentice Hall). Copyright 2006 Sun Microsystems, Inc., 9780321349804]

WordUtils.capitalizeFully() worked for me like charm as it gives: WordUtils.capitalizeFully("i am FINE") = "I Am Fine"

import java.util.Scanner;
public class TitleCase {
public static void main(String[] args) {
System.out.println("please enter the string");
Scanner sc1 = new Scanner(System.in);
String str = sc1.nextLine();
//whatever the format entered by user, converting it into lowercase
str = str.toLowerCase();
// converting string to char array for
//performing operation on individual elements
char ch[] = str.toCharArray();
System.out.println("===============");
System.out.println(str);
System.out.println("===============");
//First letter of senetence must be uppercase
System.out.print((char) (ch[0] - 32));
for (int i = 1; i < ch.length; i++) {
if (ch[i] == ' ') {
System.out.print(" " + (char) (ch[i + 1] - 32));
//considering next variable after space
i++;
continue;
}
System.out.print(ch[i]);
}
}
}

You can use lamda instead-
String titalName = Arrays.stream(names.split(" "))
.map(E -> String.valueOf(E.charAt(0))+E.substring(1))
.reduce(" ", String::concat);

Related

How do I change only letters in a string, leaving spaces, hyphens and apostrophes?

In my program, a random line (called ThingToGuess) is selected from a text file and is changed so that every letter after the third is replaced with an asterisk (this string of asterisks is called NumberOfBlanks), and the user has to guess what the original string was using the first three letters.
However, the spaces, apostrophes and hyphens must be left in the new string. For example, the string, Man in the mirror would be changed to Man ** *** ******
What I have only outputs Man *************.
String NumberOfBlanks = "";
for(int i=1; i<ThingToGuess.length(); i++){
NumberOfBlanks = NumberOfBlanks +"*";
}
String OutputCharacters = ThingToGuess.substring(0,3)+ NumberOfBlanks;
OutputCharacters = OutputCharacters.substring(0,secondIndex)+' '+OutputCharacters.substring(secondIndex+1);
System.out.println(OutputCharacters);
How do I change ThingToGuess to a string wherein only the letters are replaced with asterisks?
This should solve your problem.
String input = "Man in the mirror";
String output = input.substring(0,3) + input.substring(3,input.length()).replaceAll("[^ -\']","*");
System.out.println(output); // Prints "Man ** *** ******"
We are doing two things, taking first three characters as it is and for remaining characters, we are replacing all characters except SPACE, HYPHEN and APOSTROPHE with ASTERISK
Firstly, when you're iterating and appending to a string, its better to use a StringBuilder. As using the + operator in the loop increases the runtime of the program. More info here
Answering to your question:
String s = "Man in the mirror";
char[] charArr = s.toCharArray();
for(int i=0; i<charArr.length;i++)
{
if((charArr[i]!=' ' || charArr[i]!='\'' || charArr[i]!='-') && i>2){
charArr[i]='*';
}
}
s= new String(charArr);
System.out.println(s);
This method tackles the problem directly. It can also be solved by Regex as Hemang illustrated
You should probably use this method to check if a char is a letter or a number and convert the char to "*" only if they are.
Character.isDigit(yourchar) || Character.isLetter(yourchar)
If you are using Java 8 or 8+
public static String maskLettersAndDigits(String input) {
char[] chars = input.toCharArray();
return IntStream.range(0, chars.length).mapToObj(i -> i > 2 && Character.isLetterOrDigit(chars[i]) ? "*" : String.valueOf(chars[i])).collect(Collectors.joining());
}
Solution using regex:
public class Main {
public static void main(String[] args) {
String thingToGuess = "Man in the mirror";
String result = thingToGuess.substring(0, 3) + thingToGuess.substring(3).replaceAll("[^\\s'-]", "*");
System.out.println(result);
}
}
Output:
Man ** *** ******
The ^ inside the [] of the regex pattern specifies *None of the characters from this list of characters`.
Non-regex solution:
public class Main {
public static void main(String[] args) {
String thingToGuess = "Man in the mirror";
StringBuilder output = new StringBuilder();
output.append(thingToGuess.substring(0, 3));
for (int i = 3; i < thingToGuess.length(); i++) {
char ch = thingToGuess.charAt(i);
if (Character.isLetterOrDigit(ch)) {
output.append('*');
} else {
output.append(ch);
}
}
System.out.println(output);
}
}

Replace words in parenthesis

I have a question about replacing words. I have some strings, each of which looks like this:
String string = "today is a (happy) day, I would like to (explore) more about Java."
I need to replace the words that have parentheses. I want to replace "(happy)" with "good", and "(explore)" with "learn".
I have some ideas, but I don't know how.
for (int i = 0; i <= string.length(), i++) {
for (int j = 0; j <= string.length(), j++
if ((string.charAt(i)== '(') && (string.charAt(j) == ')')) {
String w1 = line.substring(i+1,j);
string.replace(w1, w2)
}
}
}
My problem is that I can only replace one word with one new word...
I am thinking of using a scanner to prompt me to give a new word and then replace it, how can I do this?
The appendReplacement and appendTail methods of Matcher are designed for this purpose. You can use a regex to scan for your pattern--a pair of parentheses with a word in the middle--then do whatever you need to do to determine the string to replace it with. See the javadoc.
An example, based on the example in the javadoc. I'm assuming you have two methods, replacement(word) that tells what you want to replace the word with (so that replacement("happy") will equal "good" in your example), and hasReplacement(word) that tells whether the word has a replacement or not.
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(source);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String word = m.group(1);
String newWord = hasReplacement(word) ? replacement(word) : m.group(0);
m.appendReplacement(sb, newWord); // appends the replacement, plus any not-yet-used text that comes before the match
}
m.appendTail(sb); // appends any text left over after the last match
String result = sb.toString();
Use below code for replacing the string.
String string = "today is a (happy) day, I would like to (explore) more about Java.";
string = string.replaceAll("\\(happy\\)", "good");
string = string.replaceAll("\\(explore\\)", "learn");
System.out.println(string);`
What you can do is run a loop from 0 to length-1 and if loop encounters a ( then assign its index to a temp1 variable. Now go on further as long as you encounter ).Assign its index to temp2 .Now you can replace that substring using string.replace(string.substring(temp1+1,temp2),"Your desired string")).
No need to use the nested loops. Better use one loop and store the index when you find opening parenthesis and also for close parenthesis and replace it with the word. Continue the same loop and store next index. As you are replacing the words in same string it changes the length of string you need to maintain copy of string and perform loop and replace on different,
Do not use nested for loop. Search for occurrences of ( and ). Get the substring between these two characters and then replace it with the user entered value. Do it till there are not more ( and ) combinations left.
import java.util.Scanner;
public class ReplaceWords {
public static String replaceWords(String s){
while(s.contains(""+"(") && s.contains(""+")")){
Scanner keyboard = new Scanner(System.in);
String toBeReplaced = s.substring(s.indexOf("("), s.indexOf(")")+1);
System.out.println("Enter the word with which you want to replace "+toBeReplaced+" : ");
String replaceWith = keyboard.nextLine();
s = s.replace(toBeReplaced, replaceWith);
}
return s;
}
public static void main(String[] args) {
String myString ="today is a (happy) day, I would like to (explore) more about Java.";
myString = replaceWords(myString);
System.out.println(myString);
}
}
This snippet works for me, just load the HashMap up with replacements and iterate through:
import java.util.*;
public class Test
{
public static void main(String[] args) {
String string = "today is a (happy) day, I would like to (explore) more about Java.";
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("\\(happy\\)", "good");
hm.put("\\(explore\\)", "learn");
for (Map.Entry<String, String> entry : hm.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
string = string.replaceAll(key, value);
}
System.out.println(string);
}
}
Remember, replaceAll takes a regex, so you want it to display "\(word\)", which means the slashes themselves must be escaped.

How to print a letter of a word using a number?

I'm relatively new to coding and my teacher asked us to make a code for a hangman game. He told us that we must accomplish this without the use of Arrays. My question is along the lines of this: If I have a String that is declared by the user and then a correct letter is guessed, how would I specifically be able to replace a substituted underscore with the guessed letter?
For example...
input is "cats"
system types "_ _ _ _"
say I typed the letter "a" and I want the output to be:
"_ a _ _"
How would I get the placement number of that letter and then manipulate the underscore to make it the letter?
StringBuilder.charAt()
StringBuilder.setCharAt()
You may want to have a look at these methods.
For the purpose of printing, you may want StringBuilder.toString().
You could use substrings. Something like this.
String original = "apple";
String guessed = original;
String withUnderscores = "_____";
String guess = "a";
while (guessed.contains(guess))
{
int index = guessed.indexOf(guess);
withUnderscores = withUnderscores.substring(0, index) + guess + withUnderscores.substring(index + 1);
guessed = guessed.substring(0, index) + "." + guessed.substring(index + 1);
}
System.out.println(original);
System.out.println(guessed);
Use one variable to store the underscore string. (ie "____"
Use another variable to store the answer string. (ie "cats").
Get the users input and and loop through the string taking the character at each index. If any variable matches the input letter (string1.equals(string2)) replace the character in the underscore string at whatever index your loop is at.
Use charAt() to get the character at a place in a string.
You can do this with a String or the StringBuilder class. If you haven't learned about StringBuilder in your classes, you probably shouldn't use it for your assignment.
Try something like this (I would prefer to have the guesses on a Set, it would be more clear than using a string to hold them):
public String maskUnguessedLetters(String answer, String guessed) {
Char MASKED = '_';
StringBuilder sb = new StringBuilder();
for (Char c : answer.toCharArray()) {
sb.append(guessed.contains(c.toString())
? c
: MASKED);
}
return sb.toString();
}
I don't completely understand the question, but I think this might help.
final String trueWord="cats";
String guessWord="____";
String input="a";
//if the input matches
if(trueWord.contains(input)){
//last Index of input in trueWord
int lastEntry=-1;
//hold all indices of input character in trueWord
ArrayList<Integer> indices=new ArrayList<>();
while(trueWord.indexOf(input,lastEntry+1) >= 0){
lastEntry=trueWord.indexOf(input);
indices.add(lastEntry);
}
//now replace the characters at the indices
StringBuilder newGuessWord = new StringBuilder(guessWord);
for(int index:indices){
//replace one character at a time.
newGuessWord.setCharAt(index, input.charAt(0));
}
//the new word
guessWord=newGuessWord.toString();
}
This is the not the most optimised code but will definitely give you an idea of how your task can be done.
public static void main(String[] args) {
final String word = "cats";
Scanner scanner = new Scanner(System.in);
System.out.println("Guess the character");
String finalString = "";
char letter = scanner.next().charAt(0);
for (char s : word.toCharArray()) {
if (s == letter) {
finalString += s;
} else
finalString += "_";
}
System.out.println(finalString);
scanner.close();
}

How to check if all characters in a String are all letters?

I'm able to separate the words in the sentence but I do not know how to check if a word contains a character other than a letter. You don't have to post an answer just some material I could read to help me.
public static void main(String args [])
{
String sentance;
String word;
int index = 1;
System.out.println("Enter sentance please");
sentance = EasyIn.getString();
String[] words = sentance.split(" ");
for ( String ss : words )
{
System.out.println("Word " + index + " is " + ss);
index++;
}
}
What I would do is use String#matches and use the regex [a-zA-Z]+.
String hello = "Hello!";
String hello1 = "Hello";
System.out.println(hello.matches("[a-zA-Z]+")); // false
System.out.println(hello1.matches("[a-zA-Z]+")); // true
Another solution is if (Character.isLetter(str.charAt(i)) inside a loop.
Another solution is something like this
String set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String word = "Hello!";
boolean notLetterFound;
for (char c : word.toCharArray()){ // loop through string as character array
if (!set.contains(c)){ // if a character is not found in the set
notLetterfound = true; // make notLetterFound true and break the loop
break;
}
}
if (notLetterFound){ // notLetterFound is true, do something
// do something
}
I prefer the first answer though, using String#matches
For more reference goto-> How to determine if a String has non-alphanumeric characters?
Make the following changes in pattern "[^a-zA-Z^]"
Not sure if I understand your question, but there is the
Character.isAlpha(c);
You would iterate over all characters in your string and check whether they are alphabetic (there are other "isXxxxx" methods in the Character class).
You could loop through the characters in the word calling Character.isLetter(), or maybe check if it matches a regular expression e.g. [\w]* (this would match the word only if its contents are all characters).
you can use charector array to do this like..
char[] a=ss.toCharArray();
not you can get the charector at the perticulor index.
with "word "+index+" is "+a[index];

Capitalize only the First Letter in a String java

I have been using apache WordUtils to capitalize every first letter in a String, but I need only the first letter of certain words to be capitalized and not all of them. Here is what I have:
import org.apache.commons.lang.WordUtils;
public class FirstCapitalLetter {
public static void main(String[] args) {
String str = "STATEMENT OF ACCOUNT FOR THE PERIOD OF";
str = WordUtils.capitalizeFully(str);
System.out.println(str);
}
}
My Output is:
Statement Of Account For The Period Of
I want my output to be
Statement of Account for the Period of
How can I achieve this?
1) Create a set of String you do not want to capitalize (a set of exceptions):
Set<String> doNotCapitalize = new HashSet<>();
doNotCapitalize.add("the");
doNotCapitalize.add("of");
doNotCapitalize.add("for");
...
2) Split the string by spaces
String[] words = "STATEMENT OF ACCOUNT FOR THE PERIOD OF".split(" ");
3) Iterate through the array, capitalizing only those words that are not in the set of exceptions:
StringBuilder builder = new StringBuilder();
for(String word : words){
String lower = word.toLowerCase();
if(doNotCapitalize.contains(lower){
builder.append(lower).append(" ");
}
else{
builder.append(WordUtils.capitalizeFully(lower)).append(" ");
}
}
String finalString = builder.toString();
Run WordUtils.capitalizeFully for each word in your string only if its length is longer than 3, this will work in this specific case
U need to break the string in three parts
1. Statement of
2. Account for the
3. Period of.

Categories

Resources