Reversing some words in a string - java

I need to reverse 5 or more character long words in a given string. For example:
* Given string: My name is Michael.
* Output: My name is leahciM.
Rest of the sentence stays the same, just those long words get reversed.
So far I came up with this:
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
String reversedSentence = "";
String reversedWord = "";
for (String str : splitWords) {
if (str.length() >= 5) {
for (int i = str.length() - 1; i >= 0; i--)
reversedWord += (str.charAt(i) + " ");
}
}
}
And I have reversed those words, but
1) they are in one string, without a space
2) I dont know how to put them back into their places in string

Here is a suggestion:
write a method that reverses a string:
private static String reverse(String s) { ... }
then in your main method, call it when necessary:
if (str.length() >= 5) str = reverse(str);
you then need to put the words back together, presumably into the reversedSentence string:
reversedSentence += str + " "; //you will have an extra space at the end
Side notes:
using a StringBuilder may prove more efficient than string concatenation for longer sentences.
you could put all the words back into a List<String> within the loop and call reversedSentence = String.join(" ", list) after the loop
reversing a string can be done in one line - you should find numerous related Q&As on stackoverflow.

You can use StringBuilder
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
StringBuilder builder = new StringBuilder();
for (String str : splitWords) {
if (str.length() < 5) {
builder.append(str);
else
builder.append(new StringBuilder(str).reverse().toString());
builder.append(" ");
}
return builder.toString().trim();
}

No need to use anything else you almost had it, just check your "for" loops and remember to add the unreversed string.
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
String reversedSentence = "";
String reversedWord;
for (String str : splitWords) {
if (str.length() >= 5) {
reversedWord = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversedWord += (str.charAt(i));
}
reversedSentence += " " + reversedWord;
} else {
reversedSentence += " " + str;
}
}
return reversedSentence;
}

Use StringBuilder to build the answer as you process the elements in splitWords.
You may also find the idiom of space with special first-time value (being "") useful.
There was also a bug in your original code.
So here is what I would do:
public class ReverseLongWord {
public static void main(String[] args) {
String testInput = "My name is Michael";
System.out.println(spinWords(testInput));
}
public static String spinWords(String sentence) {
String[] splitWords = sentence.split(" ");
String reversedSentence = "";
StringBuilder sb = new StringBuilder();
String space = ""; // first time special
String reversedWord = "";
for (String str : splitWords) {
if (str.length() >= 5) {
for (int i = str.length() - 1; i >= 0; i--) {
reversedWord += (str.charAt(i)); // Bug fixed
}
sb.append(space + reversedWord);
} else {
sb.append(space + str);
}
space = " "; // second time and onwards
}
return sb.toString();
}
}
The output of this program is the following, as you have specified:
My name is leahciM

I think the reverse method as some people suggest would be the easiest way, here I share my implementation
public static void main(String[] args) {
System.out.println(concatenatePhrase("My name is Michael"));
System.out.println(concatenatePhrase("Some randoms words with differents sizes and random words"));
}
private static String concatenatePhrase(String phrase) {
StringBuilder completePhrase = new StringBuilder();
String[] phrases = phrase.split(" ");
for (String word : phrases) {
if (word.length() >= 5) {
completePhrase.append(reverseWord(word).append(" "));
} else {
completePhrase.append(word).append(" ");
}
}
return completePhrase.toString().trim();
}
private static StringBuilder reverseWord(String wordPassed) {
StringBuilder word = new StringBuilder(wordPassed);
return word.reverse();
}

Related

find next word of a word from a string

I have written following code to get next word from a string in Java. I feel its very raw and I shouldn't have to write so much code for this but couldn't find any other way. Want to know if there are better ways available to do same:
public static String getNextWord(String str, String word) {
String nextWord = null;
// to remove multi spaces with single space
str = str.trim().replaceAll(" +", " ");
int totalLength = str.length();
int wordStartIndex = str.indexOf(word);
if (wordStartIndex != -1) {
int startPos = wordStartIndex + word.length() + 1;
if (startPos < totalLength) {
int nextSpaceIndex = str.substring(startPos).indexOf(" ");
int endPos = 0;
if (nextSpaceIndex == -1) {
// we've reached end of string, no more space left
endPos = totalLength;
} else {
endPos = startPos + nextSpaceIndex;
}
nextWord = str.substring(startPos, endPos);
}
}
return nextWord;
}
Note: the input word could be anything (multi words, single word, a word not in string etc).
Test:
String text = "I am very happy with life";
System.out.println(StringUtil.getNextWord(text, "I"));
System.out.println(StringUtil.getNextWord(text, "I am"));
System.out.println(StringUtil.getNextWord(text, "life"));
System.out.println(StringUtil.getNextWord(text, "with"));
System.out.println(StringUtil.getNextWord(text, "fdasfasf"));
System.out.println(StringUtil.getNextWord(text, text));
Output:
am
very
null
life
null
null
This sounds like a job for regex. Something like this:
public static String getNextWord(String str, String word){
Pattern p = Pattern.compile(word+"\\W+(\\w+)");
Matcher m = p.matcher(str);
return m.find()? m.group(1):null;
}
Hope this will serve your purpose.
public static String getNextWord(String str, String word) {
String[] words = str.split(" "), data = word.split(" ");
int index = Arrays.asList(words).indexOf((data.length > 1) ? data[data.length - 1] : data[0]);
return (index == -1) ? "Not Found" : ((index + 1) == words.length) ? "End" : words[index + 1];
}
Input (single word) :
String str = "Auto generated method stub";
String word = "method";
Out Put:
next word: stub
Input (multi-words) :
String str = "Auto generated method stub";
String word = "Auto generated";
Out Put:
next word: method
Input (missing word) :
String str = "Auto generated method stub";
String word = "was";
Out Put:
next word: Not Found
Input (end word) :
String str = "Auto generated method stub";
String word = "stub";
Out Put:
next word: End
You can create an array of words by doing this:
String[] words = str.split(" ");
This splits the string into strings when separated by a space. Note you keep needing to trim the str as you want to.
Now, you can somehow search in the array by finding some word and adding 1 to the index to get the next one.
nextword = words[words.indexOf(word) + 1];
I think, this solution works correctly:
public static String getNextWord(String str, String word) {
String[] strArr = str.split(word);
if(strArr.length > 1) {
strArr = strArr[1].trim().split(" ");
return strArr[0];
}
return null;
}
You can try the below code.
public static String getNextWord(String str, String word) {
try {
List<String> text = Arrays.asList(str.split(" "));
List<String> list = Arrays.asList(word.split(" "));
int index_of = text.indexOf(list.get(list.size() - 1));
return (index_of == -1) ? null : text.get(index_of + 1);
} catch(Exception e) {
return null;
}
}
Hope this is what you are looking for:
public static void main(String[] args) {
String text = "I am very happy with life";
System.out.println(getNextWord(text,"am"));
System.out.println(getNextWord(text,"with"));
System.out.println(getNextWord(text,"happy"));
System.out.println(getNextWord(text,"I"));
System.out.println(getNextWord(text,"life"));
}
public static String getNextWord(String text,String finditsNext){
String result = "There is no next string";
try {
int findIndex = text.indexOf(finditsNext);
String tep = text.substring(findIndex);
if(tep.indexOf(" ") >0) {
tep = tep.substring(tep.indexOf(" ") + 1);
if(tep.indexOf(" ") >0)
result = tep.substring(0, tep.indexOf(" "));
else
result = tep;
}
}catch (IndexOutOfBoundsException ex){
}
return result;
}
The output for the above is:
very
life
with
am
There is no next string

Getting error trying to reverse a string in Java

I'm trying to do a simple reverse task like: change the string "how are you" to "you are how".
this is my code:
public class Program {
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String [] retString = new String[givenString.length];
int last = givenString.length - 1;
for (int i = 0; i < givenString.length; i++) {
retString [i] = givenString[last--];
}
return retString.toString();
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
I'm getting a weird output:
[Ljava.lang.String;#e76cbf7
The output isn't "weird" at all - it's the Object's internal string representation, created by Object.toString(). String[] doesnt override that. If you want to output all entires, loop through them and concatenate them, Best using a StringBuilder to avoid creating unnecessary String instances.
public static String arrayToString (String[] array) {
StringBuilder result = new StringBuilder();
for (String value : array) {
result.append(value);
}
return StringBuilder.toString();
}
If you don'T need that method on it'S own and want to include it in the overall process of reversing the sentence, this is how it may look. It iterates only once, iterating backwards (= counting down) to reverse the sentence.
public static String revSentence (String str) {
String [] givenString = str.split(" ");
StringBuilder result = new StringBuilder();
// no need for 'last', we can use i to count down as well...
for (int i = givenString.length - 1 ; i >= 0; i--) {
result.append(givenString[i]);
}
return result.toString();
}
[Edit]: because of the OPs comment to one of the other answers, about not having learned how to use StringBUilder yet, here is a arrayToStirng method without using one. Note however that this should not be done normally, as it creates useless instances of String whiche are not cleaned up by the GC because of the immutable nature of String(all instances are kept for reuse).
public static String arrayToString (String[] array) {
String result = "";
for (String value : array) {
result += value;
}
return result;
}
Or, without a dedicate arrayToString method:
public static String revSentence (String str) {
String [] givenString = str.split(" ");
String result = "";
for (int i = givenString.length-1 ; i >= 0 ; i--) {
result += givenString[i];
}
return result;
}
Here is a solution:
public class Program {
public static String revSentence (String str) {
String retString = "";
String [] givenString = str.split(" ");
for (int i=givenString.length-1; i>=0; i--) {
retString += givenString[i] + " ";
}
return retString;
}
public static void main(String[] args) {
String m = "how are you";
System.out.print(revSentence(m));
}
}
Modified it to make the "revSentence" function return a String, plus improved the code a bit. Enjoy!
Calling toString() on an array object (in your case retString) doesn't print all array entries, instead it prints object address.
You should print array entries by iterating over them.
Use this code for reversed string
StringBuilder builder = new StringBuilder();
for(String s : retString) {
builder.append(s);
}
return builder.toString();
Calling toString on an array gives you the memory ref which isn't very useful. Try this:
public static String revSentence (String str) {
String[] givenString = str.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
sb.append(givenString[i]);
if (i != 0)
sb.append(" ");
}
return sb.toString();
}
the for loop start from greater length to lower and builder.append(givenString[i] + " "); this will concatenate String and return whole sentence you are how you could use both mySentence += givenString[i] + " "; or builder.append(givenString[i] + " "); but the best way is to use StringBuilder class (see docs)
public class Program {
public static String revSentence(String str) {
String[] givenString = str.split(" ");
String[] retString = new String[givenString.length];
int last = givenString.length - 1;
//String mySentence = "";
StringBuilder builder = new StringBuilder();
for (int i = givenString.length - 1; i >= 0; i--) {
// retString [i] = givenString[i];
// mySentence += givenString[i] + " ";
builder.append(givenString[i] + " ");
}
return builder.toString(); // retuning String
//return mySentence;
}
public static void main(String[] args) {
String m = "how are you";
System.out.println(revSentence(m));
}
}
Faster, and shorter:
To reverse a word, use:
public String reverseWord(String s) {
StringBuilder y = new StringBuilder(s);
return y.reverse();
}
Now split and use this method and use Stringbuidler.append to concatenate the all.
And dont forget the space inbetween.

Reverse string of integers while not reversing the integers themselves

I'm trying to make a function reverse a string of integers, but am only able to mirror it completely, with the following piece of code I found. (I want to translate it from string to string without arrays or lists, preferably recursively)
static String reverseMe(String s) {
if(s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
}
So for example (1 2 41) returns (14 2 1) when I really want (41 2 1). I would like some way for Java to start reversing when it encounters a space (or any none-integer) and keep the integers themselves as they are.
A modified version of your function using String#lastIndexOf:
String reverseMe(String s)
{
if (s.length() == 0)
return "";
int index = s.lastIndexOf(" ");
if (index == -1) // not found, thus just return the string
return s;
else // found, thus concat last part with recursive call
return s.substring(index + 1) + " " + reverseMe(s.substring(0, index));
}
Or you can use String#split to separate by spaces and just loop through in reverse and concatenate.
String reverse(String s)
{
String reversed = "";
String[] split = s.split(" ");
reversed = split[split.length-1];
for (int i = split.length-2; i >= 0; i--)
{
reversed += " " + split[i];
}
return reversed;
}
Although StringBuilder would make for a more efficient option, since it doesn't require all that string copying.
You can also use StringTokenized
StringTokenizer st = new StringTokenizer("1 2 41");
StringBuilder sb = new StringBuilder();
while (st.hasMoreTokens()) {
if (sb.length() > 0) {
sb.insert(0, ' ');
}
sb.insert(0, st.nextToken());
}
System.out.println(sb.toString());
One another solution among these
static String reverseMe(String s) {
if(s.length() == 0)
return "";
String sa[] = s.split(" ");
List<String> newlist = Arrays.asList(sa);
Collections.reverse(newlist);
return newlist.toString();
}
Non recursive, guava present.
String input = "123 456 789 tt 012";
Iterable<String> tokens = Splitter.on(Pattern.compile("[^\\d]")).omitEmptyStrings().split(input);
for(String token: tokens){
StringBuilder builder = new StringBuilder(token);
System.out.println(builder.reverse().toString());
}
Or without guava:
String input = "123 456 789 tt 012";
String tokens [] = input.split("[^\\d]+");
for(String token:tokens){
StringBuilder builder = new StringBuilder(token);
System.out.println(builder.reverse().toString());
}
If you want to do it recursively,this would do it!
public static String reverseIt(final String inp,final int lastIndex,String out)
{
int i=lastIndex;
while(inp.charAt(i)!=' ' && i!=-1){i--;if(i==-1)break;}
out+=(inp.substring(i+1,lastIndex+1));if(i!=-1)out+=" ";
if(lastIndex!=0)return reverseIt(inp,i-1,out);
else return out;
}
You can now call it as
reverseIt(input,input.length-1,output);
If you are not particular with recursion, the below solution would work.
static String reversMe(String str) {
StringBuffer strBuf = new StringBuffer();
String strArray = str.split(" ");
for(int i = strArray.length();i>=0; i--) {
strBuf.append(strArray[i]).append(" ");
}
return strBuf.toString().trim();
}
It can be as simple as this.
String num="1 2 41";
StringTokenizer sTok=new StringTokenizer(num, " ");
String revnum="";
while(sTok.hasMoreTokens())
{
revnum=sTok.nextToken()+" "+revnum;
}
System.out.println(revnum);
Yet another recursive variant using Tail call recursion.
public static String reverseMe(String s) {
StringBuilder sb = new StringBuilder();
return reverseMe(s.split(" "), sb);
}
public static String reverseMe(String[] s, StringBuilder sb) {
if (s.length == 0) {
return sb.toString().trim();
} else {
return reverseMe(Arrays.copyOfRange(s, 1, s.length), sb.insert(0, " ").insert(0, s[0]));
}
}

Reversing characters in each word in a sentence - Stack Implementation

This code is inside the main function:
Scanner input = new Scanner(System.in);
System.out.println("Type a sentence");
String sentence = input.next();
Stack<Character> stk = new Stack<Character>();
int i = 0;
while (i < sentence.length())
{
while (sentence.charAt(i) != ' ' && i < sentence.length() - 1)
{
stk.push(sentence.charAt(i));
i++;
}
stk.empty();
i++;
}
And this is the empty() function:
public void empty()
{
while (this.first != null)
System.out.print(this.pop());
}
It doesn't work properly, as by typing example sentence I am getting this output: lpmaxe. The first letter is missing and the loop stops instead of counting past the space to the next part of the sentence.
I am trying to achieve this:
This is a sentence ---> sihT si a ecnetnes
Per modifications to the original post, where the OP is now indicating that his goal is to reverse the letter order of the words within a sentence, but to leave the words in their initial positions.
The simplest way to do this, I think, is to make use of the String split function, iterate through the words, and reverse their orders.
String[] words = sentence.split(" "); // splits on the space between words
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.print(reverseWord(word));
if (i < words.length-1) {
System.out.print(" "); // space after all words but the last
}
}
Where the method reverseWord is defined as:
public String reverseWord(String word) {
for( int i = 0; i < word.length(); i++) {
stk.push(word.charAt(i));
}
return stk.empty();
}
And where the empty method has been changed to:
public String empty() {
String stackWord = "";
while (this.first != null)
stackWord += this.pop();
return stackWord;
}
Original response
The original question indicated that the OP wanted to completely reverse the sentence.
You've got a double-looping construct where you don't really need it.
Consider this logic:
Read each character from the input string and push that character to the stack
When the input string is empty, pop each character from the stack and print it to screen.
So:
for( int i = 0; i < sentence.length(); i++) {
stk.push(sentence.charAt(i));
}
stk.empty();
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence you want it to output elpmaxe ecnetnes not ecnetnes elpmaxe.
The reason that you see lpmaxe instead of elpmaxe is because your inner while-loop doesn't process the last character of the string since you have i < sentence.length() - 1 instead of i < sentence.length(). The reason that you only see a single word is because your sentence variable consists only of the first token of the input. This is what the method Scanner.next() does; it reads the next (by default) space-delimited token.
If you want to input a whole sentence, wrap up System.in as follows:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine().
Hope this helps.
Assuming you've already got your input in sentence and the Stack object is called stk, here's an idea:
char[] tokens = sentence.toCharArray();
for (char c : tokens) {
if (c == ' ') {
stk.empty();
System.out.print(c);
} else {
stk.add(c);
}
}
Thus, it will scan through one character at a time. If we hit a space character, we'll assume we've hit the end of a word, spit out that word in reverse, print that space character, then continue. Otherwise, we'll add the character to the stack and continue building the current word. (If you want to also allow punctuation like periods, commas, and the like, change if (c == ' ') { to something like if (c == ' ' || c == '.' || c == ',') { and so on.)
As for why you're only getting one word, darrenp already pointed it out. (Personally, I'd use a Scanner instead of a BufferedReader unless speed is an issue, but that's just my opinion.)
import java.util.StringTokenizer;
public class stringWork {
public static void main(String[] args) {
String s1 = "Hello World";
s1 = reverseSentence(s1);
System.out.println(s1);
s1 = reverseWord(s1);
System.out.println(s1);
}
private static String reverseSentence(String s1){
String s2 = "";
for(int i=s1.length()-1;i>=0;i--){
s2 += s1.charAt(i);
}
return s2;
}
private static String reverseWord(String s1){
String s2 = "";
StringTokenizer st = new StringTokenizer(s1);
while (st.hasMoreTokens()) {
s2 += reverseSentence(st.nextToken());
s2 += " ";
}
return s2;
}
}
public class ReverseofeachWordinaSentance {
/**
* #param args
*/
public static void main(String[] args) {
String source = "Welcome to the word reversing program";
for (String str : source.split(" ")) {
System.out.print(new StringBuilder(str).reverse().toString());
System.out.print(" ");
}
System.out.println("");
System.out.println("------------------------------------ ");
String original = "Welcome to the word reversing program";
wordReverse(original);
System.out.println("Orginal Sentence :::: "+original);
System.out.println("Reverse Sentence :::: "+wordReverse(original));
}
public static String wordReverse(String original){
StringTokenizer string = new StringTokenizer(original);
Stack<Character> charStack = new Stack<Character>();
while (string.hasMoreTokens()){
String temp = string.nextToken();
for (int i = 0; i < temp.length(); i ++){
charStack.push(temp.charAt(i));
}
charStack.push(' ');
}
StringBuilder result = new StringBuilder();
while(!charStack.empty()){
result.append(charStack.pop());
}
return result.toString();
}
}
public class reverseStr {
public static void main(String[] args) {
String testsa[] = { "", " ", " ", "a ", " a", " aa bd cs " };
for (String tests : testsa) {
System.out.println(tests + "|" + reverseWords2(tests) + "|");
}
}
public static String reverseWords2(String s) {
String[] sa;
String out = "";
sa = s.split(" ");
for (int i = 0; i < sa.length; i++) {
String word = sa[sa.length - 1 - i];
// exclude "" in splited array
if (!word.equals("")) {
//add space between two words
out += word + " ";
}
}
//exclude the last space and return when string is void
int n = out.length();
if (n > 0) {
return out.substring(0, out.length() - 1);
} else {
return "";
}
}
}
This can pass in leetcode

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