How to separate each word from a string in java? - java

One of my AP projects includes separating each word from a string, I have tried accomplishing numerous times yet with no success! My class has not yet learned about arrays, regex, or split yet so if you could help please avoid any of those. However we did learn substring, charAt, indexOf, length, trim ...
This is one of my attempts:
(notice that in order for me to actually notice I've split them I try adding N to the string I am re-creating, which is newWord)
public class Functions {
public static String stringReversal(String word){
if (word.length() <= 1){
return word;
}else{
char c = word.charAt(0);
return stringReversal(word.substring(1)) + c;
}
}
public static Boolean palindrome(String word){
Boolean palindrome;
if (word.equalsIgnoreCase(stringReversal(word))){
return palindrome = true;
} else{
return palindrome = false;
}
}
public static String pigLatin(String sentence){
if(sentence.length() <= 1){
return sentence;
} else {
String newWord = "";
return newWord += pigLatin(sentence.substring(0, sentence.indexOf(" "))) + " N ";
}
}
}
Main:
public class Main {
public static void main (String [] args){
Scanner in = new Scanner(System.in);
String word = in.nextLine();
System.out.println(Functions.test(word));
}
}
However the output only print N! Can anyone please help and show a way that I can accomplish this, I've tried many ideas yet none worked.

Since this seems to be highly homework-related, I will only post some hints and suggestions, you will have to combine my hints and suggestions to come up with the/a solution yourself.
I believe this:
sentence.indexOf("")
should be this: sentence.indexOf(" ")
Checking indexOf an empty string makes not much sense (it always returns zero, since the empty string can be found everywhere within a String).
public static void main(String[] args) {
String word = "a bit of words";
System.out.println(test(word));
}
public static String test(String sentence){
if(sentence.length() <= 1){
return sentence;
} else {
String newWord = "";
return newWord += test(sentence.substring(0, sentence.indexOf(" "))) + " N ";
}
}
The above prints: a N
However, if your input is only one word then sentence.indexOf(" ") will return -1. You will need to check this. Suggestion: Modify your if-statement to instead check if string contains a space character or not.
To solve the assignment, you will need some kind of loop (recursion can also be a kind of loop) to repeat a slightly modified process for each word. Hint: Fetch the first word, then fetch the original String except for the extracted word.

public static void main( String[] args )
{
Scanner in = new Scanner( System.in );
try
{
while( true )
{
String word = in.nextLine();
System.out.println( splitWords( word ) );
}
}
finally
{
in.close();
}
}
private static String splitWords( String s )
{
int splitIndex = s.indexOf( ' ' );
if( splitIndex >= 0 )
return s.substring( 0, splitIndex ) + " N " + splitWords( s.substring( splitIndex + 1 ) );
return s;
}

you can use standard method String#split()
String[] words = sentence.split(' ');
note than words is an array

Related

Method that corrects the text, inserting spaces after the comma in Java

I want to create a refactorSeparators method that takes an object of the String type as an argument. Method returns the text from the input object corrected so that if there is any
a comma or a period and there is no space after it, it will insert this space.I'm stuck, don't know what to do next, below is my code. How can I finish it? I wonder how to write this part: if (s.equals(".") && i.next().equals())
public class Separator {
public static void main(String[] args) {
String text = "Periods,hyphens, the last two characters cannot be a period. The rest of them don't. And there you go.";
ArrayList<String> stringArr = new ArrayList<>();
String[] arrOfStr = text.split("");
Iterator i = stringArr.iterator();
for (String s : arrOfStr) {
stringArr.add(s);
System.out.println("{" +s + "}");
}
for (String s : arrOfStr) {
if (s.equals(".") && i.next().equals()) {
String space = " ";
stringArr.add(i.next(, " ");
} else {
System.out.println("error");
}
}
}}
You're over-thinking it:
String refactorSeparators(String str) {
return str.replaceAll("([,.]) ?", "$1 ").trim();
}
The regex ([,.]) ? matches a comma or dot optionally followed by a space, which is replaced with the dot/comma and a space. The trim() removes the space that would be added if there's a dot at the end of the input.
Your main problem is here:
Iterator i = stringArr.iterator();
// ...
for (String s : arrOfStr) {
if (s.equals(".") && i.next().equals()) {
You are iterating both with an iterator and a for-loop, that makes life complicated. I'd suggest using a for-loop over the index.
Also your second equals expression is missing an argument.
Since Bohemian already posted the regex one liner, I might as well post my solution too:
public class PunctuationFixer {
private String text;
private int index;
public static String addMissingWhitespaceAfterPunctuation(String input) {
return new PunctuationFixer(input).fix();
}
private PunctuationFixer(String input) {
this.text = input;
this.index = 0;
}
private String fix() {
while (index < this.text.length() - 1) {
fix(this.text.charAt(index));
index++;
}
return this.text;
}
private void fix(char current) {
if (current == '.' || current == ',') {
addSpaceIfNeeded();
}
}
private void addSpaceIfNeeded() {
if (' ' != (text.charAt(index + 1))) {
text = text.substring(0, index + 1) + " " + text.substring(index + 1);
index++;
}
}
public static void main(String[] args) {
String text = "Periods,hyphens, the last two characters cannot be a period. The rest of them don't. And there you go.";
System.out.println(addMissingWhitespaceAfterPunctuation(text));
}
}
That's an typical parse issue. You have to remember the last char you've read and deppendend on your current char, you know what to do.
public static void main(String[] args) {
String text = "Periods,hyphens, the last two characters cannot be a period.The rest of them don't. And there you go.";
StringBuilder fixedString = new StringBuilder();
String[] arrOfStr = text.split("");
String lastChar = null;
for(String currentChar : arrOfStr) {
if(lastChar != null && (lastChar.equals(",") || lastChar.equals(".")) && !currentChar.equals(" "))
fixedString.append(" ");
fixedString.append(currentChar);
lastChar = currentChar;
}
System.out.println(fixedString);
}
Side note: The shortest and most elegant solution is, of course, #bohemian's. But I suspect it is not in the sense of the homework! ;-)

Reverse the words in Java with recursively

public class PrintElements {
public static void printReverse (String str)
{
if ((str==null)||(str.length() <= 1))
System.out.print(str);
else
{
System.out.print(str.charAt(str.length()-1));
printReverse(str.substring(0,str.length()-1));
}
}
/**
* #param args
*/
public static void main(String[] args) {
String str="this function reverse";
printReverse(str);
}
}
In this method, I am trying to just change the place the words not letters place with using recursion.
For example, if "this function reverse" is the input, the output should be "Reverse function this".
But my current output is : "esrever noitcnuf siht"
Do it as follows:
import java.util.Arrays;
public class Main {
public static void printReverse(String str) {
if (str == null || !str.contains(" ")) {
System.out.print(str);
return;
}
String[] words = str.split("\\s+");// Split str on space(s)
System.out.print(words[words.length - 1] + " ");// Print the last element
// Call the method recursively by passing a new string with all but last word
printReverse(String.join(" ", Arrays.asList(words).subList(0, words.length - 1)));
}
public static void main(String[] args) {
String str = "this function reverse";
printReverse(str);
}
}
Output:
reverse function this
Try this. It traverses the input string and finds out each word and then merges them into the reversed string by reversing the order of the words.
public static void printReverse (String str)
{
if ((str == null) || (str.equals("")))
return ;
str = str + " "; //to add a space at the end. this will help in detecting the last word
String revStr = "", word = "";
char c;
for (int i=0; i < str.length(); i++)
{
c = str.charAt(0);
if (c != ' ')
{
word = word + c;
}
else
{
revStr = word + " " + revStr;
}
}
System.out.println(revStr.Trim()); //removes the extra space from the end
}
}
public static String reverseString(String str) {
if (str == null)
return "";
if (!str.contains(" "))
return str;
int whitespacePos = str.indexOf(" ");
String firstWord = str.substring(0, whitespacePos);
return reverseString(str.substring(whitespacePos + 1)) + " " + firstWord;
}
public static void main(String[] args) {
String str = "this function reverse";
System.out.println(reverseString(str));
}
I tested this code and it works
It is (most of the time) cleaner to return a String, and then print this String if you want to.
If you use charAt(), you are only getting individual characters. Therefore it will be difficult to not also reverse the letters of the words. It is easier to find the whitespaces between the words and then to retrieve whole words with subString()
the subString() method can take two parameters, startIndex and endIndex, or just one parameter, only the startIndex. It then returns the subString from this startIndex up to the end of the String.
Note: I know you can use split(), I wanted to show how it can be done with indexes. If you already use split(), you might aswell not use recursion.
public static void reverseWords(String str){
if(str=="" || str==null){
return;
}else {
String[] _str = str.split(" ");
System.out.println(_str[_str.length-1]);
String[] newArr = Arrays.copyOf(_str,_str.length-1);
reverseWords(String.join(" ", newArr));
}
}
dont forget to import
import java.util.Arrays;
public String reverseString(String str){
if(str.lastIndexOf(32) ==-1){ //32 is an ASCII value for space
return str;
}
return str.substring(str.lastIndexOf(32)+1)+" "+reverseString(str.substring(0,str.lastIndexOf(32)));
//Here lastIndexOf() method get the last element of space so that method substring takes the String after last space because is used lastIndexOf(32)+1 and
//reverseString() method continuously takes up to n-1 from nth string until lastIndexOf() return -1 i.e no more whitespace avaliable
}
Here's a solution:
public String reverseString(final String str){
//Using ternary operator
return (str.lastIndexOf(32) == -1)
? str
: str.substring(str.lastIndexOf(32) + 1) + " " + reverseString(str.substring(0, str.lastIndexOf(32)));
}
or with if-else:
public String reverseString(final String str){
if (str.lastIndexOf(32) == -1))
return str;
else
return str.substring(str.lastIndexOf(32) + 1) + " " + reverseString(str.substring(0, str.lastIndexOf(32)));
}
32 is the space character. So if there's no space in the string it just returns the string (word). If there is one it recursively swaps the tail after the and the word before it.

How to recursively take an input string and return a string with each character repeated?

Basically I have an assignment that requires me to write a method called stutter. The stutter method is supposed to take an input String s and return the string with each character repeated. For example, if the input string was "help" then the result of running this method should be "hheellpp". I have tried a bunch of different things and can't get it to work. Here is my code:
import java.util.*;
public class Stutter {
static String stutterString = "";
public static String stutter ( String s ) {
char ch = s.charAt (0);
String tempString = String.valueOf ( ch );
if ( s.length() == 0 ) {
return stutterString;
} else {
stutterString += tempString + tempString;
return stutter ( s.substring (1) );
}
}
public static void main ( String [] args ) {
Scanner inputScanner = new Scanner ( System.in );
System.out.println ( "What word would you like to stutter?" );
String userInput = inputScanner.next();
inputScanner.close();
System.out.println ( stutter ( userInput ) );
}
}
I get an error that I'm not sure what to do with. This is the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Stutter.stutter(Stutter.java:12)
at Stutter.stutter(Stutter.java:23)
at Stutter.main(Stutter.java:41)
Any help would be appreciated. This isn't a huge program. As you can see, I've posted the entire Stutter class that I'm using. It's just bugging me because I'm sure there is a simple fix to this, but I'm not seeing it.
You need to change this line
char ch = s.charAt (0);
to
char ch = s.length() > 0 ? s.charAt(0) : ' ';
And your code will work as expected.
A better and clearer solution would be:
if (s.length() == 0) {
return stutterString;
} else {
char ch = s.charAt(0);
String tempString = String.valueOf(ch);
stutterString += tempString + tempString;
return stutter(s.substring (1));
}
What word would you like to stutter?
>> abcdefg
>> aabbccddeeffgg
Explanation:
What will happen when you try to s.charAt(0) when s is an empty String? You're not verifying that s is not empty, adding the simple check s.length() > 0 is what you're missing.
Tip: Always use the debugger, it's there to help you, you'll better understand the flow of your program when you use it. Also when writing a recursion, using a pencil and a paper to draw the calls will help you to understand it.
I did it like this:
My base case is when the length of the string is less than 1, in which case it will return "".
Otherwise it will print of the first character of the string twice, and then call the stutter method again.
I pass in the original string as a parameter, except I have removed the first character from it.In this way the 2nd character of the original string will be printed out twice next and the string gets shorter.
import java.util.*;
public class Stutter {
public static String stutter ( String s ) {
if(s.length() < 1) return "";
else{
return "" + s.charAt(0) + s.charAt(0) + stutter(s.substring(1,s.length()));
}
}
public static void main ( String [] args ) {
Scanner s = new Scanner ( System.in );
System.out.println ( "What word would you like to stutter?" );
String userInput = s.nextLine();
System.out.println(stutter(userInput));
}
}
Hint: if s.length() is zero, then s.charAt(0) will throw an exception ... because you are trying to fetch a character beyond the end of the zero-length string.
Check the length of your s variable before s.charAt (0). For example, move
char ch = s.charAt (0);
String tempString = String.valueOf ( ch );
to else block
How about this:
public class Stutter {
private static String head(String str) {
return str.substring(0,1);
}
private static String tail(String str) {
return str.substring(1);
}
private static String stutter(String str) {
if (str.length() > 0)
return head(str)+head(str)+stutter(tail(str));
else
return "";
}
public static void main(String args[]) throws Exception {
if (args.length > 0) {
System.out.println(stutter(args[0]));
}
}
}
This can be achieved very simply using String.replaceAll():
public class Stutter {
public static void main (String args[]) {
String TEST_STRING = "abcdefg";
System.out.println(stutter(TEST_STRING));
}
private static String stutter(String s) {
return s.replaceAll("(.)", "$1$1");
}
}
Editted.
import java.util.*;
public class Stutter {
static String stutterString = "";
public static String stutter ( String s ) {
if(s.length() > 0)
{
return stutterString.concat(s.substring(0,1)).concat(s.substring(0,1)).concat(stutter(s.substring(1)));
}
else
{
return stutterString;
}
}
public static void main ( String [] args ) {
Scanner inputScanner = new Scanner ( System.in );
System.out.println ( "What word would you like to stutter?" );
String userInput = inputScanner.next();
inputScanner.close();
System.out.println ( stutter ( userInput ) );
}
}

How do i remove the whitespace?

I'm trying to create a palindrome tester program for my AP Java class and I need to remove the white spaces in my code completely but it's not letting me do so.
import java.util.Scanner;
public class Palin{
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
public static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i-=1) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c))
{
dest.append(c);
}
}
return dest.toString();
}
public static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
System.out.print("Enter Palindrome: ");
Scanner sc = new Scanner(System.in);
String string = sc.next();
String str = string;
String space = "";
String result = str.replaceAll("\\W", space);
System.out.println(result);
System.out.println();
System.out.println("Testing palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(result)) {
System.out.println("It's a palindrome!");
} else {
System.out.println("Not a palindrome!");
}
System.out.println();
}
}
Any help would be greatly appreciated.
Seems like your code is fine except for the following. You are using
String string = sc.next();
which will not read the whole line of input, hence you will lose part of the text. I think you should use the following instead of that line.
String string = sc.nextLine();
If you just want to remove the beginning and ending whitespace, you can use the built in function trim(), e.g. " abcd ".trim() is "abcd"
If you want to remove it everywhere, you can use the replaceAll() method with the whitespace class as the parameter, e.g. " abcd ".replaceAll("\W","").
Use a StringTokenizer to remove " "
StringTokenizer st = new StringTokenizer(string," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
String result = t;
System.out.println(result);
I haven't actually tesed this, but have you considered the String.replaceAll(String regex, String replacement) method?
public static String removeJunk (String string) {
return string.replaceAll (" ", "");
}
Another thing to look out for is that while removing all non-digit/alpha characters removeJunk also reverses the string (it starts from the end and then appends one character at a time).
So after reversing it again (in reverse) you are left with the original and it will always claim that the given string is a palindrome.
You should use the String replace(char oldChar, char newChar) method.
Although the name suggests that only the first occurrence will be replaced, fact is that all occurrences will be replaced. The advantage of this method is that it won't use regular expressions, thus is more efficient.
So give a try to string.replace(' ', '');

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

Categories

Resources