Im a beginner java programmer and I am stuck on a little problem with my university coursework.
Basically I have a string that I want to iterate through and replace all instances of the letter 'a' or 'e' with the letter 'z'. For example, if the original string was "hello alan", the final string should be "hzllo zlzn".
We need to do this using a character array which holds the characters 'a' and 'e' to test against the string.
I've included my code below, we need to use the charAt() method also.
public static void main(String[] args) {
String a = ("what's the craic?");
char letters[] = new char[]{'a', 't'};
System.out.println("Before:" + a);
System.out.println("After: " + removeCharacters(a, letters));
}
public static String removeCharacters(String sentence, char[] letters) {
for (int i = 0; i < sentence.length(); i++) {
for (int j = 0; j < letters.length; j++) {
if (sentence.charAt(i) == letters[j]) {
sentence = sentence.replace(sentence.charAt(i), 'z');
} else {
sentence = "No changes nessesary";
}
}
}
return sentence;
}
Please help me with this problem. Im not sure where I am going wrong! Thanks.
if You are allowed to use replaceAll as well
"hello alan".replaceAll( "[ae]", "z" ); // hzllo zlzn
In difference to replace uses replaceAll a Pattern internally, which is compiled from the first argument [ae] to find the part to substitute with the second argument z. This solution is elegantly short, but slow, because the Pattern has to be compiled each time replaceAll is called.
otherwise use a StringBuilder
char[] letters = new char[] { 'a', 'e' };
StringBuilder buf = new StringBuilder( "hello alan" );
IntStream.range( 0, buf.length() ).forEach( i -> {
for( char c : letters )
if( buf.charAt( i ) == c )
buf.replace( i, i + 1, "z" );
} );
String s = buf.toString(); // hzllo zlzn
In difference to a String the contents of a StringBuilder is mutual (means you can change it). So it only has to be created once and all substitutions can be made in place.
Try this:
public static void main(String[] args) {
String a = "hello alan";
System.out.println("Before:" + a);
System.out.println("After: " + removeCharacters(a));
}
public static String removeCharacters(String sentence) {
if (!sentence.contains("a|e"))
return "No changes necessary";
return sentence.replaceAll("a|e", "z");
}
output 1:
Before:hello alan
After: hzllo zlzn
output 2:
Before:hi world
After: No changes necessary
Since you're forced to use charAt(...), one way would be like this:
public static String removeCharacters(String sentence, char[] letters) {
String output = "";
boolean wasChanged = false;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
for (int j = 0; j < letters.length; j++)
if (ch == letters[j]) {
ch = 'z';
wasChanged = true;
break;
}
output += ch;
}
if (wasChanged)
return output;
else
return "No changes necessary";
}
Since String::replace(char oldChar, char newChar) returns a new string resulting from replacing all occurrences of oldChar in this string with newChar, you do not need nested loops to do it. An efficient way of doing it can be as follows:
public static String removeCharacters(String sentence, char[] letters) {
String copy = sentence;
for (char letter : letters) {
sentence = sentence.replace(letter, 'z');
}
if (sentence.equals(copy)) {
sentence = "No changes nessesary";
}
return sentence;
}
Demo:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(removeCharacters("hello stackoverflow", new char[] { 'a', 'e' }));
System.out.println(removeCharacters("world", new char[] { 'a', 'e' }));
}
public static String removeCharacters(String sentence, char[] letters) {
String copy = sentence;
for (char letter : letters) {
sentence = sentence.replace(letter, 'z');
}
if (sentence.equals(copy)) {
sentence = "No changes nessesary";
}
return sentence;
}
}
Output:
hzllo stzckovzrflow
No changes nessesary
Related
I'm trying to figure out how to use a loop to append the delimiter ":" before the String s is found to contain a letter A-F.
If I have s = "10584f" then I would want the output to be "10584:f"
How should I go about doing this?
This is a simple solution that checks if it contains letters between a to f and put `:' accordingly.
public static void main(String[] args) {
String s = "10584f";
String newString = "";
for(int i=0;i<s.length();i++) {
if((int)s.charAt(i)>= (int)'a' && (int)s.charAt(i)<= (int)'f') {
newString = newString + ":" + s.charAt(i);
}else {
newString = newString + s.charAt(i);
}
}
System.out.println(newString);
}
You need to check for the ASCII code of each character and append the delimiter before it on this condition:
public class Main {
public static void main(String[] args) {
String s = "10584f";
System.out.println(appendDelimiter(s));
}
private static String appendDelimiter(String s) {
StringBuilder sb = new StringBuilder();
for(char c : s.toCharArray()) {
int charCode = (int) c;
if((charCode >= 65 && charCode <= 70) || (charCode >= 97 && charCode <= 102))
sb.append(":");
sb.append(c);
}
return sb.toString();
}
}
Output:
10584:f
If your target string consists of digits followed by a single letter from A-F or a-f, a simple solution can be: replacement of the regex-match, (\\d+)([A-Fa-f]). This regex means group(1) consisting of digits and group(2) consisting of a letter from A-F or a-f. The regex can be replaced with $1:$2 where $1 and $2 specify group(1) and group(2) respectively.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "10584f", "12345A", "13456b", "23456F" };
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll("(\\d+)([A-Fa-f])", "$1:$2");
}
// After replacement
System.out.println(Arrays.toString(arr));
}
}
Output:
[10584:f, 12345:A, 13456:b, 23456:F]
However, if the string can have multiple letters followed by digits and you want each letter to be prepended with a :, you can iterate the string starting from the index, 1 until the last character of the string and if you come across a letter, prepend it with a : as done in the function, withColonBeforeLetters given below:
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "10584f", "12345A", "13456b", "23456F", "1abc", "123aBc" };
for (int i = 0; i < arr.length; i++) {
arr[i] = withColonBeforeLetters(arr[i]);
}
// After replacement
System.out.println(Arrays.toString(arr));
}
static String withColonBeforeLetters(String s) {
StringBuilder sb = new StringBuilder();
// Put the first letter into sb
sb.append(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) {
sb.append(':').append(ch);
} else {
sb.append(ch);
}
}
return sb.toString();
}
}
Output:
[10584:f, 12345:A, 13456:b, 23456:F, 1:a:b:c, 123:a:B:c]
Main
public class Main
{
public static void main(String[] args)
{
System.out.println(Dupe.Eliminate("Testing UppeR and loweR"));
System.out.println(Dupe.Eliminate("UppeR is BetteR"));
}
}
Class
public class Dupe
{
public static String Eliminate(String input)
{
char[] chrArray = input.toCharArray();
String letter ="";
for (char value:chrArray){
if (letter.indexOf(value) == -1){
letter += value;
}
}
return letter;
}
}
I am trying to eliminate duplicate letters e.g. Hello would be Helo. Which I have achieved, however, what I want to implement is that it won't matter if it's uppercase or lowercase, it will still be classed as a duplicate so Hehe would be He, not Heh. Should I .equals... each individual letter or is there an efficient way? sorry for asking if it's simple question for you guys.
This is how I would approach this. This might not be the most efficient way to do it, but you can try this.
public class Main
{
public static void main(String[] args)
{
System.out.println(Dupe.Eliminate("Testing UppeR and loweR"));
}
}
class Dupe
{
public static String Eliminate(String input)
{
char[] chrArray = input.toCharArray();
String letter ="";
for(int index = 0; index < chrArray.length; index++)
{
int j = 0;
boolean flag = true;
//this while loop is used to check if the next character is already existed in the string (ignoring the uppercase or lowercase)
while(j < letter.length())
{
if((int)chrArray[index] == letter.charAt(j) || (int)chrArray[index] == ((int)letter.charAt(j)+32) ) //32 is because the difference between the ascii value of the uppercase and lowercase letter is 32
{
flag = false;
break;
}
else
j++;
}
if(flag == true)
{
letter += chrArray[index];
}
}
return letter;
}
}
you can have 2 checks in place with upper case and lower case characters:
public static String Eliminate(String input)
{
char[] chrArray = input.toCharArray();
String letter ="";
for (char value:chrArray){
if (letter.indexOf(value.toLowerCase()) == -1 && letter.indexOf(value.toUpperCase()) == -1){
letter += value;
}
}
return letter;
}
Here you go, this will replace all duplicate characters no matter how many in the sequence.
public static void main(String[] args)
{
String duped = "aaabbccddeeffgg";
final Pattern p = Pattern.compile("(\\w)\\1+");
final Matcher m = p.matcher(duped);
while (m.find())
System.out.println("Duplicate character " + (duped = duped.replaceAll(m.group(), m.group(1))));
}
If you are looking for duplicates like: abacd to replace both a's, try this as the regex given in Pattern.compile(".*([0-9A-Za-z])\\1+.*")
Here's another (stateful) way to do it:-
String s = "Hehe";
Set<String> found = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
String result = s.chars()
.mapToObj(c -> "" + (char) c)
.filter(found::add)
.collect(Collectors.joining());
System.out.println(result);
Output: He
I have an assignment for school due at midnight today. I have finished almost all the assignment except for one question. I need to swap "r" and "q" with each other as values. So, if you enter "r" in the compiler you should get "q" if you enter "q" you get "r"(Using JOptionPane). For example, if your name is Quart, the compiler should print Ruaqt. I tried using the replace.All method, but once I can only swap "r" or "q" not both. I know I need a temporary variable, but do not know anything else...
We had to replace vowels with the letter after them so I did this:
String firstName = JOptionPane
.showInputDialog("What is your first name?");
String lastName = JOptionPane
.showInputDialog("What is your last name?");
String fullname = firstname + lastname;
String lowername = fullName.toLowerCase();
String encryptedname = lowername.replaceAll("a", "b")
.replaceAll("e", "f").replaceAll("i", "j").replaceAll("o", "p")
.replaceAll("u", "v");
Thanks
Dunno why the 2 answers using StringBuilder are both making the thing more complicated than needed.
Here is the way you can use StringBuilder to do that single character swap:
public static String swapChar(String string, char c1, char c2) {
StringBuilder sb = new StringBuilder(string);
for (int i = 0; i < sb.length(); ++i) {
if (sb.charAt(i) == c1) {
sb.setCharAt(i, c2);
} else if (sb.charAt(i) == c2) {
sb.setCharAt(i, c1);
}
}
return sb.toString();
}
Update :
Just found that what you are looking for is actually doing a bunch of replace of character at the same time. That can be cleanly done by providing a Map as parameter:
public static String replaceChars(String string, Map<Character,Character> cmap) {
StringBuilder sb = new StringBuilder(string);
for (int i = 0; i < sb.length(); ++i) {
if (cmap.containsKey(sb.charAt(i)) {
sb.setCharAt(i, cmap.get(sb.charAt(i));
}
}
return sb.toString();
}
to use it:
// or make a util method to make these even easier to create
Map<Character,Character> cmap = new HashMap<Character,Character>();
cmap.put('r','q');
cmap.put('q','r');
cmap.put('a','b');
cmap.put('e','f');
cmap.put('i','j');
cmap.put('o','p');
cmap.put('u','v');
and simply do a replace:
String result = replaceChars(inputString, cmap);
or even simpler, by making use of Apache Commons Lang:
String result = StringUtils.replaceChars(inputString, "rqaeiou", "qrbfjpv");
You can try this.
private static final char Q_STR = 'q';
private static final char R_STR = 'r';
public static String replaceString(String original, int position, char strToReplace) {
StringBuilder strBuilder = new StringBuilder(original);
if (strToReplace == Q_STR) {
strBuilder.setCharAt(position, R_STR);
} else if (strToReplace == R_STR){
strBuilder.setCharAt(position, Q_STR);
}
return strBuilder.toString();
}
public static void main(String[] args) {
String firstname = "Quart";
String lastname = " QuartLastName";
String fullname = firstname + lastname;
String lowername = fullname.toLowerCase();
//get all chars in String
char[] array = lowername.toCharArray();
//list to keep original position of Q char
List<Integer> allQPosition = new ArrayList<Integer>();
//list to keep original position of R char
List<Integer> allRPosition = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
if(array[i] == 'q') {
allQPosition.add(i);
} else if(array[i] == 'r') {
allRPosition.add(i);
}
}
//replace q
for (Integer integer : allQPosition) {
lowername = replaceString(lowername, integer, Q_STR);
}
//replace r
for (Integer integer : allRPosition) {
lowername = replaceString(lowername, integer, R_STR);
}
//replace others
String encryptedname = lowername.replace("a", "b")
.replace("e", "f")
.replace("i", "j")
.replace("o", "p")
.replace("u", "v");
System.out.println("Result: " + encryptedname);
}
My solution is:
Keep all position of 'q' and 'r' from original String.
Replace each of them
Replace the rest of other chars
Hope this help
public static void main(String[] args) {
String origin = "r and q";
System.out.println(newReplacement(origin, 'r', 'q'));
}
private static String newReplacement(String origin, char firstChar, char secondChar) {
StringBuffer stringBuffer = new StringBuffer(origin);
for(int i = 0; i < origin.length(); i++) {
if(origin.charAt(i) == firstChar) {
stringBuffer.replace(i, i+1, secondChar + "");
continue;
}
if(origin.charAt(i) == secondChar) {
stringBuffer.replace(i, i+1, firstChar + "");
}
}
return stringBuffer.toString();
}
Rewrite replace method with simple one.
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
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