String substring error - java

Question:
Input:-gandhi output:- Gandhi
Input:-mahatma gandhi output:- M. Gandhi
Input:-Mohndas Karamchand ganDhi output:- M. K. Gandhi
Answer:
public class Chef_NITIKA {
static Scanner scan=new Scanner(System.in);
public static void main(String[] args) {
String name= myString();
System.out.println("nam is :"+name);
mySformatter(name);
}
private static void mySformatter(String name) {
int count=0;
for(char c:name.toCharArray()){
if(c==' '){
count+=1;
}
}
System.out.println(count+" blank spaces");
if(count==0){
char ch=name.charAt(0);
name=Character.toUpperCase(ch)+name.substring(1);
System.out.println("nam is :"+name);
}
else if(count==1){
char ch=name.charAt(0);
name= name.replace(' ', '.');
String subname=name.substring(name.indexOf(".")+1);
char c=subname.charAt(0);
subname=Character.toUpperCase(c)+subname.substring(1);
name=Character.toUpperCase(ch)+"."+subname;
System.out.println("nam is :"+name);
}
else if(count==2){
char ch=name.charAt(0);
// name= name.replace(' ', '.');
String subname=name.substring(name.indexOf(" ")+1);
System.out.println(subname);
String subsubname=subname.substring(name.indexOf(" "));
System.out.println(subsubname);
char c=subname.charAt(0);
char c1=subsubname.charAt(0);
subname=Character.toUpperCase(c)+subname.substring(1);
name = Character.toUpperCase(ch)+"."+Character.toUpperCase(c)+"."+Character.toUpperCase(c1)+subsubname.substring(1);
System.out.println("nam is :"+name);
}
}
private static String myString() {
System.out.println("enter the string");
String s=scan.nextLine();
StringBuffer name=new StringBuffer();
// name.append(s);
return s;
}
}
I am not getting the desired output when i type "abc cde fgh" i get the output as A.C..fgh
Is there any efficient way to solve this problem?
undesired output:-
enter the string
iam writing onStack
nam is :iam writing onStack
2 blank spaces
writing onStack
ing onStack
nam is :I.W.Ing onStack
I want the output as I.W.OnStack

Just split the name into components and then form the abbreviations you want:
public static String getName(String input) {
String[] names = input.split("\\s+");
String output = "";
// replace 1st through second to last names with capitalized 1st letter
for (int i=names.length; i > 1; --i) {
output += names[names.length - i].substring(0, 1).toUpperCase() + ". ";
}
// append full last name, first letter capitalized, rest lower case
output += names[names.length - 1].substring(0, 1).toUpperCase()
+ names[names.length - 1].substring(1).toLowerCase();
return output;
}
public static void main(String[] args) {
System.out.println(getName("gandhi"));
System.out.println(getName("mahatma gandhi"));
System.out.println(getName("Mohndas Karamchand ganDhi"));
}
Output:
Gandhi
M. Gandhi
M. K. Gandhi
Demo here:
Rextester
Update:
Here is a link to a demo where I have corrected your original code, at least partially. The issue was the following line:
String subsubname = subname.substring(name.indexOf(" "));
which I changed to this:
String subsubname = subname.substring(subname.indexOf(" ") + 1);
You were not correctly identifying the first character of the third portion of the name. This being said, your current approach is verbose, hard to read, and inflexible. In practice, you would probably want to use a leaner approach to this problem.

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stack;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
*
* #author xxz
*/
public class NAmes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final String name = sc.nextLine();
System.out.println(formatedString(name));
sc.close();
}
private static String formatedString(String name) {
if(name!=null && name.length()!=0){
final StringTokenizer tokenizer = new StringTokenizer(name, " ");
StringBuilder result = new StringBuilder("");
while(tokenizer.hasMoreTokens()){
StringBuilder currentToken =new StringBuilder(tokenizer.nextToken());
if(!tokenizer.hasMoreTokens()){
result.append(currentToken.toString().toUpperCase());
} else{
result.append(currentToken.toString().toUpperCase().charAt(0)+". ");
}
}
return result.toString();
}
return "";
}
}

#Rushabh Oswal you can get desired result by below method
private static void mySformatter(String name) {
String [] tempArray=name.split(" ");
StringBuilder outputStr=new StringBuilder();
int len=tempArray.length;
for(int i=0;i<len;i++){
String str=tempArray[i];
if (str.isEmpty())
continue;
if(i==len-1)
outputStr.append(Character.toUpperCase(str.charAt(0))).append(str.substring(1).toLowerCase());
else
outputStr.append(Character.toUpperCase(str.charAt(0))).append(". ");
System.out.println(outputStr.toString());
}

Related

StringTokenizer: 'NoSuchElementException' and a few other problems

In this program, I have a String with words separated by spaces and I want to remove a particular word and then print the new String. This is my code below:
import java.util.*;
class A
{
public static void main()
{
String str="Monday Tuesday Wednesday";
String newstr="";
StringTokenizer S=new StringTokenizer(str);
while(S.hasMoreTokens()==true)
{
if(S.nextToken().equals("Tuesday"))
{
continue;
}
else
newstr=newstr+(S.nextToken()+" ");
}
System.out.println(newstr);
}
}
In the above code, I want to delete the word 'Tuesday' from the String, and print the new String. But when I run the program, the following exception is thrown:
When I want to remove the word 'Wednesday' after changing the code, only 'Tuesday' is shown on Output screen. Likewise, when I want to remove 'Monday', only 'Wednesday' is shown as output.
I would really like some help on this so that I that I can understand the 'StringTokenizer' class better.
Thank You!
StringTokenizer.nextToken() increments the token upon each call. You should only call it once per loop, and save the value it returns in the local scope.
import java.util.StringTokenizer;
class A {
public static void main(String[] args) {
String str = "Monday Tuesday Wednesday";
String newstr = "";
StringTokenizer S = new StringTokenizer(str);
while(S.hasMoreTokens() == true) {
String day = S.nextToken();
if(day.equals("Tuesday")) {
continue;
} else {
newstr = newstr + (day + " ");
}
}
System.out.println(newstr);
}
}
returns Monday Wednesday
public class A {
public static void main(String[] a) {
String str = "Monday Tuesday Wednesday";
String newstr = "";
StringTokenizer S = new StringTokenizer(str," ");
while (S.hasMoreTokens()) {
String token = S.nextToken();
if (token.equals("Tuesday")) {
continue;
} else
newstr = newstr + (token + " ");
}
System.out.println(newstr);
}
}
you have to take nextToken only once

Remove space and Uppercase first letter

I made this program which shall turn around sentences like:
User Input: Hello i´m hungry. Where is the fridge.
System Output: Hungry i´m Hello. Fridge the is Where.
But there is space between the last word and "." in the reversed sentence. How can i remove? And how can i make the first word a uppercase word?
package etzale;
public class etzale {
public static void main(String[] args) {
StringBuilder outputString= new StringBuilder();
String satz;
System.out.print("Bitte geben Sie einen String ein: ");
String text="Hallo mir gehts gut. Wie gehts dir. mir gehts spitze.";
while(text.indexOf(".")>=0){
satz=text.substring(0, text.indexOf("."));
text=text.substring(text.indexOf(".")+1);
String []s= satz.split(" ");
for(int i=s.length-1; i>=0; i--){
outputString.append(s[i]);
if(s[0]==" ");
outputString.append(" ");
}
outputString.append(".");
outputString.append(" ");
}
System.out.print(outputString);
}
}
How can i erase the space between the last word and "." in each sentence?
Actual Input: Mit gehts gut. Wie gehts dir. Mir gehts spitze.
Actual Output: gut gehts mir . dir gehts Wie . spitze gehts Mir .
I already answer another you almost similar question: Reverse all words, set "." and do the same for the next sentences, my solution covered this case also try it:
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
final String userInput = "Hello i´m hungry. Where is the fridge.";
final String expectedResult = "Hungry i´m Hello. Fridge the is Where.";
String[] sentences = userInput.split("\\. ");
String reversedSentences = Stream.of(sentences)
.map(sentenceString -> new Sentence(sentenceString))
.map(Sentence::reverse)
.map(Sentence::firstLetterToUpperCase)
.map(Sentence::removeAllDots)
.map(Sentence::dotInTheEnd)
.map(Sentence::toString)
.collect(Collectors.joining(" "));
System.out.println(reversedSentences.equals(expectedResult)); //returns true
}
}
final class Sentence {
private final String sentence;
Sentence(String sentence) {
this.sentence = sentence;
}
Sentence reverse() {
String[] words = sentence.split(" ");
Collections.reverse(Arrays.asList(words));
return new Sentence(String.join(" ", words));
}
Sentence firstLetterToUpperCase() {
String firstLetter = sentence.substring(0, 1);
String anotherPart = sentence.substring(1);
return new Sentence(firstLetter.toUpperCase() + anotherPart);
}
Sentence dotInTheEnd() {
return new Sentence(sentence + ".");
}
Sentence removeAllDots() {
return new Sentence(sentence.replaceAll("\\.", ""));
}
public String toString() {
return sentence;
}
}
OK, appart from your code not being very appealing, you have a typo in your code that is causing you trouble:
outputString.append(" ");
Remove that semicolon at the end and you will not have spaces before dots.
Here's the way I would do it. Performs at lot less inefficient string concatenation, and handles full stops, question marks, and exclamation marks.
public static void main(String[] args) {
System.out.println("Bitte geben Sie einen String ein: ");
String text = "Hallo mir gehts gut!! Wie gehts dir. mir gehts spitze.";
System.out.println(reverseSentences(text));
}
/**
* Reverse the order of the words in the sentence.
* #param sentence the sentence to reverse.
* #param terminal the symbol to add at the end.
* #return the reversed sentence, with added terminal.
*/
static String reverse(String sentence, String terminal) {
sentence = sentence.trim();
if (sentence.isEmpty()) {
return terminal;
}
// find words by splitting the sentence at spaces
// then put the words back together in reverse order
String[] words = sentence.split("\\s+");
StringBuilder sb = new StringBuilder(sentence.length());
for (int i = words.length - 1; i >= 0; i--) {
String word = words[i];
// capitalize the last word before placing it at the start
if (i == words.length - 1 && !word.isEmpty()) {
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1));
} else {
sb.append(word);
}
if (i > 0) sb.append(' ');
}
// append terminal
sb.append(terminal);
return sb.toString();
}
/**
* Reverse each sentence in the string.
* #param s the string to act on.
* #return the string, with sentences reversed.
*/
public static String reverseSentences(String s) {
// Match each sentence, with an optional terminal
// terminal may be one or more
// full stops, question or exclamation marks
Pattern p = Pattern.compile("([^.?!]+)([.?!]*)");
Matcher m = p.matcher(s);
// find and reverse the sentences, then recombine them
StringBuilder sb = new StringBuilder(s.length());
while (m.find()) {
String sentence = m.group(1);
String terminal = m.group(2);
sb.append(reverse(sentence, terminal));
sb.append(' ');
}
return sb.toString().trim();
}

How to add whitespace before a string

I need your help in adding whitespace before a string as I need to format the String value to be in a specific position in the page. For example:
System.out.println(" Hello Word!!");
The above will give 10 spaces before the String which I did them manual, but is there any other way to specify the space before the String other than adding manual spaces?
Consider this as your code....
public static void main(String[] args) {
String hello = "hello";
Brute b = new Brute();
System.out.println( b.addspace(1,hello));
}
String addspace(int i, String str)
{
StringBuilder str1 = new StringBuilder();
for(int j=0;j<i;j++)
{
str1.append(" ");
}
str1.append(str);
return str1.toString();
}
This will add desired no of spaces in the string at its beginning...
Just pass your input String and no of spaces needed....
As addspace(<no_of_spaces>,<input_string>);
String newStr = String.format("%10s", str);
String str = "Hello Word!!";
String.format("%1$" + (10 + str.length()) + "s", str);
Result:
| Hello Word!!|
10 whitespaces added
You can write your own fumction:
public static void main(String[] args) {
String myString = "Hello Word!!";
System.out.println(getWhiteSpace(10)+myString);
}
private static String getWhiteSpace(int size) {
StringBuilder builder = new StringBuilder(size);
for(int i = 0; i <size ; i++) {
builder.append(' ');
}
return builder.toString();
}
This may be useful to you,
String s = "%s Hellow World!";
StringBuilder builder = new StringBuilder();
for(int i=0;i<10;i++){
builder.append(" ");
}
System.out.println(s.format(s,builder.toString()));
You can change the modify the count of space in the for loop.
import java.io.*;
import java.util.*;
class spaceBeforeString
{
public static void main(String args[])
{
String str="Hello";
for(int i=0;i<10;i++)
{
str=" "+str;
}
System.out.println(str);
}
}
import java.util.*;
import java.io.*;
class AddSpaceDemo
{
String str;
int noOfSpaces;
Scanner sc=new Scanner(System.in);
void getInput()
{
System.out.println("Enter the string before which the space is to be added: ");
str=sc.next();
System.out.println("Enter the no. of spaces to be added before the string: ");
noOfSpaces=sc.nextInt();
}
String addSpaceBefore()
{
for(int i=0;i<noOfSpaces;i++)
{
str=" "+str;
}
return str;
}
}
class AddSpace
{
public static void main(String args[])
{
String s;
AddSpaceDemo a=new AddSpaceDemo();
a.getInput();
s=a.addSpaceBefore();
System.out.println("String after adding whitespace before string: ");
System.out.println(s);
}
}
I'm making a basic Java POS System. You set how many characters fits on the paper width and it align both to the left and to the right.
public class Main {
int width = 32;
public static void main(String[] args) {
String dash = "--------------------------------";
String item = "COMPANY NAME";
String price = "00.00";
String string = alignment(item, price);
String description = "123-456-7890";
String tax = "0.00";
String string2 = alignment(description, tax);
System.out.println(dash);
System.out.println(string);
System.out.println(string2);
}
private static String alignment(String item, String price) {
String s = "";
s += item;
int x = 0;
while(x < width - item.length() - price.length()) {
s += " ";
x++;
}
s += price;
return s;
}
}

How to capitalize the first character of each word in a string

Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?
Examples:
jon skeet -> Jon Skeet
miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
old mcdonald -> Old Mcdonald*
*(Old McDonald would be find too, but I don't expect it to be THAT smart.)
A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.
WordUtils.capitalize(str) (from apache commons-text)
(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)
If you're only worried about the first letter of the first word being capitalized:
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
Try this very simple way
example givenString="ram is good boy"
public static String toTitleCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
Output will be: Ram Is Good Boy
I made a solution in Java 8 that is IMHO more readable.
public String firstLetterCapitalWithSingleSpace(final String words) {
return Stream.of(words.trim().split("\\s"))
.filter(word -> word.length() > 0)
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}
The Gist for this solution can be found here: https://gist.github.com/Hylke1982/166a792313c5e2df9d31
String toBeCapped = "i want this sentence capitalized";
String[] tokens = toBeCapped.split("\\s");
toBeCapped = "";
for(int i = 0; i < tokens.length; i++){
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();
I've written a small Class to capitalize all the words in a String.
Optional multiple delimiters, each one with its behavior (capitalize before, after, or both, to handle cases like O'Brian);
Optional Locale;
Don't breaks with Surrogate Pairs.
LIVE DEMO
Output:
====================================
SIMPLE USAGE
====================================
Source: cApItAlIzE this string after WHITE SPACES
Output: Capitalize This String After White Spaces
====================================
SINGLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string ONLY before'and''after'''APEX
Output: Capitalize this string only beforE'AnD''AfteR'''Apex
====================================
MULTIPLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)
Output: Capitalize This String After Spaces, BeforE'apex, And #After And BeforE# Number Sign (#)
====================================
SIMPLE USAGE WITH CUSTOM LOCALE
====================================
Source: Uniforming the first and last vowels (different kind of 'i's) of the Turkish word D[İ]YARBAK[I]R (DİYARBAKIR)
Output: Uniforming The First And Last Vowels (different Kind Of 'i's) Of The Turkish Word D[i]yarbak[i]r (diyarbakir)
====================================
SIMPLE USAGE WITH A SURROGATE PAIR
====================================
Source: ab 𐐂c de à
Output: Ab 𐐪c De À
Note: first letter will always be capitalized (edit the source if you don't want that).
Please share your comments and help me to found bugs or to improve the code...
Code:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class WordsCapitalizer {
public static String capitalizeEveryWord(String source) {
return capitalizeEveryWord(source,null,null);
}
public static String capitalizeEveryWord(String source, Locale locale) {
return capitalizeEveryWord(source,null,locale);
}
public static String capitalizeEveryWord(String source, List<Delimiter> delimiters, Locale locale) {
char[] chars;
if (delimiters == null || delimiters.size() == 0)
delimiters = getDefaultDelimiters();
// If Locale specified, i18n toLowerCase is executed, to handle specific behaviors (eg. Turkish dotted and dotless 'i')
if (locale!=null)
chars = source.toLowerCase(locale).toCharArray();
else
chars = source.toLowerCase().toCharArray();
// First charachter ALWAYS capitalized, if it is a Letter.
if (chars.length>0 && Character.isLetter(chars[0]) && !isSurrogate(chars[0])){
chars[0] = Character.toUpperCase(chars[0]);
}
for (int i = 0; i < chars.length; i++) {
if (!isSurrogate(chars[i]) && !Character.isLetter(chars[i])) {
// Current char is not a Letter; gonna check if it is a delimitrer.
for (Delimiter delimiter : delimiters){
if (delimiter.getDelimiter()==chars[i]){
// Delimiter found, applying rules...
if (delimiter.capitalizeBefore() && i>0
&& Character.isLetter(chars[i-1]) && !isSurrogate(chars[i-1]))
{ // previous character is a Letter and I have to capitalize it
chars[i-1] = Character.toUpperCase(chars[i-1]);
}
if (delimiter.capitalizeAfter() && i<chars.length-1
&& Character.isLetter(chars[i+1]) && !isSurrogate(chars[i+1]))
{ // next character is a Letter and I have to capitalize it
chars[i+1] = Character.toUpperCase(chars[i+1]);
}
break;
}
}
}
}
return String.valueOf(chars);
}
private static boolean isSurrogate(char chr){
// Check if the current character is part of an UTF-16 Surrogate Pair.
// Note: not validating the pair, just used to bypass (any found part of) it.
return (Character.isHighSurrogate(chr) || Character.isLowSurrogate(chr));
}
private static List<Delimiter> getDefaultDelimiters(){
// If no delimiter specified, "Capitalize after space" rule is set by default.
List<Delimiter> delimiters = new ArrayList<Delimiter>();
delimiters.add(new Delimiter(Behavior.CAPITALIZE_AFTER_MARKER, ' '));
return delimiters;
}
public static class Delimiter {
private Behavior behavior;
private char delimiter;
public Delimiter(Behavior behavior, char delimiter) {
super();
this.behavior = behavior;
this.delimiter = delimiter;
}
public boolean capitalizeBefore(){
return (behavior.equals(Behavior.CAPITALIZE_BEFORE_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}
public boolean capitalizeAfter(){
return (behavior.equals(Behavior.CAPITALIZE_AFTER_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}
public char getDelimiter() {
return delimiter;
}
}
public static enum Behavior {
CAPITALIZE_AFTER_MARKER(0),
CAPITALIZE_BEFORE_MARKER(1),
CAPITALIZE_BEFORE_AND_AFTER_MARKER(2);
private int value;
private Behavior(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Using org.apache.commons.lang.StringUtils makes it very simple.
capitalizeStr = StringUtils.capitalize(str);
From Java 9+
you can use String::replaceAll like this :
public static void upperCaseAllFirstCharacter(String text) {
String regex = "\\b(.)(.*?)\\b";
String result = Pattern.compile(regex).matcher(text).replaceAll(
matche -> matche.group(1).toUpperCase() + matche.group(2)
);
System.out.println(result);
}
Example :
upperCaseAllFirstCharacter("hello this is Just a test");
Outputs
Hello This Is Just A Test
With this simple code:
String example="hello";
example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());
System.out.println(example);
Result: Hello
I'm using the following function. I think it is faster in performance.
public static String capitalize(String text){
String c = (text != null)? text.trim() : "";
String[] words = c.split(" ");
String result = "";
for(String w : words){
result += (w.length() > 1? w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1, w.length()).toLowerCase(Locale.US) : w) + " ";
}
return result.trim();
}
Use the Split method to split your string into words, then use the built in string functions to capitalize each word, then append together.
Pseudo-code (ish)
string = "the sentence you want to apply caps to";
words = string.split(" ")
string = ""
for(String w: words)
//This line is an easy way to capitalize a word
word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())
string += word
In the end string looks something like
"The Sentence You Want To Apply Caps To"
This might be useful if you need to capitalize titles. It capitalizes each substring delimited by " ", except for specified strings such as "a" or "the". I haven't ran it yet because it's late, should be fine though. Uses Apache Commons StringUtils.join() at one point. You can substitute it with a simple loop if you wish.
private static String capitalize(String string) {
if (string == null) return null;
String[] wordArray = string.split(" "); // Split string to analyze word by word.
int i = 0;
lowercase:
for (String word : wordArray) {
if (word != wordArray[0]) { // First word always in capital
String [] lowercaseWords = {"a", "an", "as", "and", "although", "at", "because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"};
for (String word2 : lowercaseWords) {
if (word.equals(word2)) {
wordArray[i] = word;
i++;
continue lowercase;
}
}
}
char[] characterArray = word.toCharArray();
characterArray[0] = Character.toTitleCase(characterArray[0]);
wordArray[i] = new String(characterArray);
i++;
}
return StringUtils.join(wordArray, " "); // Re-join string
}
public static String toTitleCase(String word){
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
public static void main(String[] args){
String phrase = "this is to be title cased";
String[] splitPhrase = phrase.split(" ");
String result = "";
for(String word: splitPhrase){
result += toTitleCase(word) + " ";
}
System.out.println(result.trim());
}
1. Java 8 Streams
public static String capitalizeAll(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Arrays.stream(str.split("\\s+"))
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
.collect(Collectors.joining(" "));
}
Examples:
System.out.println(capitalizeAll("jon skeet")); // Jon Skeet
System.out.println(capitalizeAll("miles o'Brien")); // Miles O'Brien
System.out.println(capitalizeAll("old mcdonald")); // Old Mcdonald
System.out.println(capitalizeAll(null)); // null
For foo bAR to Foo Bar, replace the map() method with the following:
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
2. String.replaceAll() (Java 9+)
ublic static String capitalizeAll(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Pattern.compile("\\b(.)(.*?)\\b")
.matcher(str)
.replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
}
Examples:
System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
System.out.println(capitalizeAll("i am atta")); // I Am Atta
System.out.println(capitalizeAll(null)); // null
3. Apache Commons Text
System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
System.out.println(WordUtils.capitalize(null)); // null
For titlecase:
System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!
For details, checkout this tutorial.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence : ");
try
{
String str = br.readLine();
char[] str1 = new char[str.length()];
for(int i=0; i<str.length(); i++)
{
str1[i] = Character.toLowerCase(str.charAt(i));
}
str1[0] = Character.toUpperCase(str1[0]);
for(int i=0;i<str.length();i++)
{
if(str1[i] == ' ')
{
str1[i+1] = Character.toUpperCase(str1[i+1]);
}
System.out.print(str1[i]);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
I decided to add one more solution for capitalizing words in a string:
words are defined here as adjacent letter-or-digit characters;
surrogate pairs are provided as well;
the code has been optimized for performance; and
it is still compact.
Function:
public static String capitalize(String string) {
final int sl = string.length();
final StringBuilder sb = new StringBuilder(sl);
boolean lod = false;
for(int s = 0; s < sl; s++) {
final int cp = string.codePointAt(s);
sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
lod = Character.isLetterOrDigit(cp);
if(!Character.isBmpCodePoint(cp)) s++;
}
return sb.toString();
}
Example call:
System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs: 𐐪𐐪."));
Result:
An À La Carte String. Surrogate Pairs: 𐐂𐐪.
Use:
String text = "jon skeet, miles o'brien, old mcdonald";
Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
}
String capitalized = matcher.appendTail(buffer).toString();
System.out.println(capitalized);
There are many way to convert the first letter of the first word being capitalized. I have an idea. It's very simple:
public String capitalize(String str){
/* The first thing we do is remove whitespace from string */
String c = str.replaceAll("\\s+", " ");
String s = c.trim();
String l = "";
for(int i = 0; i < s.length(); i++){
if(i == 0){ /* Uppercase the first letter in strings */
l += s.toUpperCase().charAt(i);
i++; /* To i = i + 1 because we don't need to add
value i = 0 into string l */
}
l += s.charAt(i);
if(s.charAt(i) == 32){ /* If we meet whitespace (32 in ASCII Code is whitespace) */
l += s.toUpperCase().charAt(i+1); /* Uppercase the letter after whitespace */
i++; /* Yo i = i + 1 because we don't need to add
value whitespace into string l */
}
}
return l;
}
package com.test;
/**
* #author Prasanth Pillai
* #date 01-Feb-2012
* #description : Below is the test class details
*
* inputs a String from a user. Expect the String to contain spaces and alphanumeric characters only.
* capitalizes all first letters of the words in the given String.
* preserves all other characters (including spaces) in the String.
* displays the result to the user.
*
* Approach : I have followed a simple approach. However there are many string utilities available
* for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException{
System.out.println("Input String :\n");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String inputString = in.readLine();
int length = inputString.length();
StringBuffer newStr = new StringBuffer(0);
int i = 0;
int k = 0;
/* This is a simple approach
* step 1: scan through the input string
* step 2: capitalize the first letter of each word in string
* The integer k, is used as a value to determine whether the
* letter is the first letter in each word in the string.
*/
while( i < length){
if (Character.isLetter(inputString.charAt(i))){
if ( k == 0){
newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
k = 2;
}//this else loop is to avoid repeatation of the first letter in output string
else {
newStr = newStr.append(inputString.charAt(i));
}
} // for the letters which are not first letter, simply append to the output string.
else {
newStr = newStr.append(inputString.charAt(i));
k=0;
}
i+=1;
}
System.out.println("new String ->"+newStr);
}
}
Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result += Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
This is just another way of doing it:
private String capitalize(String line)
{
StringTokenizer token =new StringTokenizer(line);
String CapLine="";
while(token.hasMoreTokens())
{
String tok = token.nextToken().toString();
CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";
}
return CapLine.substring(0,CapLine.length()-1);
}
Reusable method for intiCap:
public class YarlagaddaSireeshTest{
public static void main(String[] args) {
String FinalStringIs = "";
String testNames = "sireesh yarlagadda test";
String[] name = testNames.split("\\s");
for(String nameIs :name){
FinalStringIs += getIntiCapString(nameIs) + ",";
}
System.out.println("Final Result "+ FinalStringIs);
}
public static String getIntiCapString(String param) {
if(param != null && param.length()>0){
char[] charArray = param.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);
}
else {
return "";
}
}
}
Here is my solution.
I ran across this problem tonight and decided to search it. I found an answer by Neelam Singh that was almost there, so I decided to fix the issue (broke on empty strings) and caused a system crash.
The method you are looking for is named capString(String s) below.
It turns "It's only 5am here" into "It's Only 5am Here".
The code is pretty well commented, so enjoy.
package com.lincolnwdaniel.interactivestory.model;
public class StringS {
/**
* #param s is a string of any length, ideally only one word
* #return a capitalized string.
* only the first letter of the string is made to uppercase
*/
public static String capSingleWord(String s) {
if(s.isEmpty() || s.length()<2) {
return Character.toUpperCase(s.charAt(0))+"";
}
else {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
/**
*
* #param s is a string of any length
* #return a title cased string.
* All first letter of each word is made to uppercase
*/
public static String capString(String s) {
// Check if the string is empty, if it is, return it immediately
if(s.isEmpty()){
return s;
}
// Split string on space and create array of words
String[] arr = s.split(" ");
// Create a string buffer to hold the new capitalized string
StringBuffer sb = new StringBuffer();
// Check if the array is empty (would be caused by the passage of s as an empty string [i.g "" or " "],
// If it is, return the original string immediately
if( arr.length < 1 ){
return s;
}
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
}
Here we go for perfect first char capitalization of word
public static void main(String[] args) {
String input ="my name is ranjan";
String[] inputArr = input.split(" ");
for(String word : inputArr) {
System.out.println(word.substring(0, 1).toUpperCase()+word.substring(1,word.length()));
}
}
}
//Output : My Name Is Ranjan
For those of you using Velocity in your MVC, you can use the capitalizeFirstLetter() method from the StringUtils class.
String s="hi dude i want apple";
s = s.replaceAll("\\s+"," ");
String[] split = s.split(" ");
s="";
for (int i = 0; i < split.length; i++) {
split[i]=Character.toUpperCase(split[i].charAt(0))+split[i].substring(1);
s+=split[i]+" ";
System.out.println(split[i]);
}
System.out.println(s);
package corejava.string.intern;
import java.io.DataInputStream;
import java.util.ArrayList;
/*
* wap to accept only 3 sentences and convert first character of each word into upper case
*/
public class Accept3Lines_FirstCharUppercase {
static String line;
static String words[];
static ArrayList<String> list=new ArrayList<String>();
/**
* #param args
*/
public static void main(String[] args) throws java.lang.Exception{
DataInputStream read=new DataInputStream(System.in);
System.out.println("Enter only three sentences");
int i=0;
while((line=read.readLine())!=null){
method(line); //main logic of the code
if((i++)==2){
break;
}
}
display();
System.out.println("\n End of the program");
}
/*
* this will display all the elements in an array
*/
public static void display(){
for(String display:list){
System.out.println(display);
}
}
/*
* this divide the line of string into words
* and first char of the each word is converted to upper case
* and to an array list
*/
public static void method(String lineParam){
words=line.split("\\s");
for(String s:words){
String result=s.substring(0,1).toUpperCase()+s.substring(1);
list.add(result);
}
}
}
If you prefer Guava...
String myString = ...;
String capWords = Joiner.on(' ').join(Iterables.transform(Splitter.on(' ').omitEmptyStrings().split(myString), new Function<String, String>() {
public String apply(String input) {
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
}
}));
String toUpperCaseFirstLetterOnly(String str) {
String[] words = str.split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++) {
ret.append(Character.toUpperCase(words[i].charAt(0)));
ret.append(words[i].substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
return ret.toString();
}

How to upper case every first letter of word in a string? [duplicate]

This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 3 years ago.
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Here is the code
String source = "hello good old world";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
i dont know if there is a function but this would do the job in case there is no exsiting one:
String s = "here are a bunch of words";
final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
if(i>0) result.append(" ");
result.append(Character.toUpperCase(words[i].charAt(0)))
.append(words[i].substring(1));
}
import org.apache.commons.lang.WordUtils;
public class CapitalizeFirstLetterInString {
public static void main(String[] args) {
// only the first letter of each word is capitalized.
String wordStr = WordUtils.capitalize("this is first WORD capital test.");
//Capitalize method capitalizes only first character of a String
System.out.println("wordStr= " + wordStr);
wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
// This method capitalizes first character of a String and make rest of the characters lowercase
System.out.println("wordStr = " + wordStr );
}
}
Output :
This Is First WORD Capital Test.
This Is First Word Capital Test.
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
i = b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());
System.out.println(b.toString());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.
public static String UppercaseFirstLetters(String str)
{
boolean prevWasWhiteSp = true;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isLetter(chars[i])) {
if (prevWasWhiteSp) {
chars[i] = Character.toUpperCase(chars[i]);
}
prevWasWhiteSp = false;
} else {
prevWasWhiteSp = Character.isWhitespace(chars[i]);
}
}
return new String(chars);
}
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
Also you can take a look into StringUtils library. It has a bunch of cool stuff.
My code after reading a few above answers.
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
*
* #param pWord
* String to be made more readable
* #return Human-readable string
*/
public static String humanize2(String pWord)
{
StringBuilder sb = new StringBuilder();
String[] words = pWord.replaceAll("_", " ").split("\\s");
for (int i = 0; i < words.length; i++)
{
if (i > 0)
sb.append(" ");
if (words[i].length() > 0)
{
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1)
{
sb.append(words[i].substring(1));
}
}
}
return sb.toString();
}
import java.util.Scanner;
public class CapitolizeOneString {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Please enter Your word = ");
String str=scan.nextLine();
printCapitalized( str );
} // end main()
static void printCapitalized( String str ) {
// Print a copy of str to standard output, with the
// first letter of each word in upper case.
char ch; // One of the characters in str.
char prevCh; // The character that comes before ch in the string.
int i; // A position in str, from 0 to str.length()-1.
prevCh = '.'; // Prime the loop with any non-letter character.
for ( i = 0; i < str.length(); i++ ) {
ch = str.charAt(i);
if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) )
System.out.print( Character.toUpperCase(ch) );
else
System.out.print( ch );
prevCh = ch; // prevCh for next iteration is ch.
}
System.out.println();
}
} // end class
public class WordChangeInCapital{
public static void main(String[] args)
{
String s="this is string example";
System.out.println(s);
//this is input data.
//this example for a string where each word must be started in capital letter
StringBuffer sb=new StringBuffer(s);
int i=0;
do{
b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
i=b.indexOf(" ",i)+1;
} while(i>0 && i<sb.length());
System.out.println(sb.length());
}
}
package com.raj.samplestring;
/**
* #author gnagara
*/
public class SampleString {
/**
* #param args
*/
public static void main(String[] args) {
String[] stringArray;
String givenString = "ramu is Arr Good boy";
stringArray = givenString.split(" ");
for(int i=0; i<stringArray.length;i++){
if(!Character.isUpperCase(stringArray[i].charAt(0))){
Character c = stringArray[i].charAt(0);
Character change = Character.toUpperCase(c);
StringBuffer ss = new StringBuffer(stringArray[i]);
ss.insert(0, change);
ss.deleteCharAt(1);
stringArray[i]= ss.toString();
}
}
for(String e:stringArray){
System.out.println(e);
}
}
}
Here is an easy solution:
public class CapitalFirstLetters {
public static void main(String[] args) {
String word = "it's java, baby!";
String[] wordSplit;
String wordCapital = "";
wordSplit = word.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
}
System.out.println(wordCapital);
}}
public String UpperCaseWords(String line)
{
line = line.trim().toLowerCase();
String data[] = line.split("\\s");
line = "";
for(int i =0;i< data.length;i++)
{
if(data[i].length()>1)
line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
else
line = line + data[i].toUpperCase();
}
return line.trim();
}
So much simpler with regexes:
Pattern spaces=Pattern.compile("\\s+[a-z]");
Matcher m=spaces.matcher(word);
StringBuilder capitalWordBuilder=new StringBuilder(word.substring(0,1).toUpperCase());
int prevStart=1;
while(m.find()) {
capitalWordBuilder.append(word.substring(prevStart,m.end()-1));
capitalWordBuilder.append(word.substring(m.end()-1,m.end()).toUpperCase());
prevStart=m.end();
}
capitalWordBuilder.append(word.substring(prevStart,word.length()));
Output for input: "this sentence Has Weird caps"
This Sentence Has Weird Caps

Categories

Resources