Java - Make character after space uppercase? - java

I'm trying to have the letter after every space turn uppercase. Can someone tell me what's wrong with the following method? Given phrase "this is a test" it returns "ThIs Is A TesT" instead of "this Is A Test"
public String toTitleCase(String phrase) {
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
phrase = phrase.replace(phrase.substring(i+1,i+2),phrase.substring(i+1,i+2).toUpperCase());
}
}
return phrase;
}

The problem in your code is that String.replace replaces each target character present in the String, and not only the one you want.
You could work directly on an array of chars instead of on the String:
public static String toTitleCase(String phrase) {
// convert the string to an array
char[] phraseChars = phrase.toCharArray();
for (int i = 0; i < phraseChars.length - 1; i++) {
if(phraseChars[i] == ' ') {
phraseChars[i+1] = Character.toUpperCase(phraseChars[i+1]);
}
}
// convert the array to string
return String.valueOf(phraseChars);
}

It's replacing all t, try below code.
It will help you.
String phrase="this is a test";
for (int i=0; i<phrase.length(); i++) {
if(phrase.substring(i,i+1).equals(" ")) {
System.out.println(phrase.substring(i+1,i+2));
phrase = phrase.replace(phrase.substring(i,i+2),phrase.substring(i,i+2).toUpperCase());
}
}
System.out.println(phrase);

Use streams (or split) to split your string into parts, don't do it manually using substring.
Try below code
String test = "this is a test";
UnaryOperator<String> capitalize = str ->
str.substring(0,1).toUpperCase() + str.substring(1).toLowerCase();
String result =
Stream.of(
test.split(" ")
).map(capitalize)
.collect(
Collectors.joining(" ")
);
System.out.println(result);
Output: This Is A Test

When you replace a substring it will replace the each occurrence of that substring - which is not necessarily the one you are trying to replace. This is why it is replacing letters inside words.
Switching to a StringBuilder here to poke individual characters. Note that we don't traverse the entire String because there is no next-character to capitalize at the last character.
public String toTitleCase(String phrase) {
StringBuilder sb = new StringBuilder(phrase);
for (int index = 0 ; index < phrase.length - 1 ; ++index) {
if (sb.charAt(index) == ' ') {
sb.setCharAt(index + 1, Character.toUppercase(sb.charAt(index + 1)));
}
}
return sb.toString();
}

If a letter is first in any word, it will be replaced everywhere. In your case, all t,i and a will be uppercase.
Taking example for is. It is find a space before. Than in if body, what actually happen:
phrase = phrase.replace("i","I");
And all i are replaced with I.
String class cannot replace at a specific position.
You have to options:
using StringBuilder which can replace at a specific position.
String toTitleCase(String phrase) {
StringBuilder sb= new StringBuilder(phrase);
for (int i=0; i<phrase.length(); i++) {
if(i==0 || phrase.charAt(i-1)==' ') {
sb.replace(i,i+1,phrase.substring(i,i+1).toUpperCase());
}
}
return sb.toString();
}
or with stream, which is the method I prefer because is one-line. This way you don't preserve white-spaces( multiple consecutive white-spaces will be replaced with only one space), but usually you want this.
Arrays.asList(phrase.split("\\s+")).stream().map(x->x.substring(0,1).toUpperCase()+x.substring(1)).collect(Collectors.joining(" "));

Related

Is there any other way to remove all whitespaces in a string?

I have a programming homework. It says that I need to reverse the string first, then change it to uppercase and then remove all the whitespaces. I actually did it, but our professor didn't say anything about using replaceAll() method. Is there any other way to do it beside replaceAll()?
Here is my code:
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
System.out.println(reverse.toUpperCase().replaceAll("\\s", ""));
}
You can check each character in turn using Character.isWhitespace. Additionally, it is generally better to use a StringBuilder when concatenating inside a loop.
public static void main(String[] args) {
String line = "the quick brown fox";
StringBuilder sb = new StringBuilder(line.length());
for (int i = line.length() - 1; i >= 0; i--) {
char c = line.charAt(i);
if(!Character.isWhitespace(c)) sb.append(Character.toUpperCase(c));
}
System.out.println(sb);
}
#Khelwood's answer as code:
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
char currentChar = line.charAt(i);
if (currentChar != ' ') {
reverse += currentChar;
}
}
System.out.println(reverse.toUpperCase());
}
Character#isWhitespace
Initialize a StringBuilder object and iterate through each character of the uppercased string. While iterating, use Character#isWhitespace to check if the character is a whitespace character. If not, append the character to the StringBuilder object. After the loop is finished, the StringBuilder object will have all characters except the whitespace characters.
public class Main {
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
String upperCased = reverse.toUpperCase();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < upperCased.length(); i++) {
char ch = upperCased.charAt(i);
if (!Character.isWhitespace(ch)) {
sb.append(ch);
}
}
System.out.println("The given string: " + line);
System.out.println("The reverse of the given string: " + reverse);
System.out.println("The reverse of the given string in UPPER case: " + upperCased);
System.out.println("After removing all space from the reverse of the given string in UPPER case: " + sb);
}
}
Output:
The given string: the quick brown fox
The reverse of the given string: xof nworb kciuq eht
The reverse of the given string in UPPER case: XOF NWORB KCIUQ EHT
After removing all space from the reverse of the given string in UPPER case: XOFNWORBKCIUQEHT
Note:
If you want to convert sb to a String, use sb.toString().
You can use String instead of StringBuilder but I recommend you use StringBuilder instead of String for such a case because repeated string concatenation in a loop creates additional as many instances of String as the number of concatenation. Check this discussion to learn more about it.
to strictly follow the professors description (and intentions?):
public static void main(String[] args) {
String line = "the quick brown fox";
String reverse = "";
for (int i = line.length() - 1; i >= 0; i--) {
reverse = reverse + line.charAt(i);
}
String upperCase = reverse.toUpperCase();
String noSpaces = "";
for (int i = 0; i < upperCase.length(); i++) {
char ch = upperCase.charAt(i);
if (!Character.isWhitespace(ch)) {
noSpaces = noSpaces + ch; // or noSpaces += ch;
}
}
System.out.println(noSpaces);
}
Note 1: this can all be done with one loop, but that would not match the description (or no (user)loop at all?).
Note 2: the use of StringBuilder is not needed anymore (when using an actual Java version (>= 11)) - actually I believe it is more efficient not to use it, the compiler does better job (see StringConcatFactory)
Note 3: if allowed to use StringBuilder, it also has a reverse method
Note 4: be aware (for future) that replaceAll() works with regular expression, very powerful, but kind of overkill to just replace a char - replace() would be more moderate
Even without using replaceAll() it’s still a one-liner:
String reverse =
new StringBuilder(line)
.reverse()
.toString()
.toUpperCase()
.replace(" ", "");
Here are two ways. The first uses a standard loop.
String line = "the quick brown fox";
StringBuilder sb = new StringBuilder();
for (int i = line.length() - 1; i >= 0; i--) {
char ch;
if ((ch = line.charAt(i)) != ' ') {
sb.append(Character.toUpperCase(ch));
}
}
System.out.println(sb.toString());
Prints
XOFNWORBKCIUQEHT
The second makes use of StringBuilder and replaceAll. And regardless, you should ask your professor since nothing was overtly forbidden.
String str = new StringBuilder("the quick brown fox")
.reverse().toString().replaceAll("\\s+", "").toUpperCase();
System.out.println(str);
Also prints
XOFNWORBKCIUQEHT
You can use String.codePoints method to iterate over int values of the characters of this string, to reverse their order, change to uppercase and remove whitespaces:
String line = "the quick brown fox";
String reverse = line
// return IntStream
.codePoints()
// return Stream<Character>
.mapToObj(ch -> (char) ch)
// reverse the order
// of characters once
.sorted((ch1, ch2) -> -1)
// change to uppercase
.map(Character::toUpperCase)
// remove whitespaces
.filter(ch -> !Character.isWhitespace(ch))
// return Stream<String>
.map(String::valueOf)
// join strings with
// characters back
// to a single string
.collect(Collectors.joining());
System.out.println(reverse); // XOFNWORBKCIUQEHT
See also: Is there a way to reverse specific arrays in a multidimensional array?
If you do not need to store the reversed line, you can also just iterate it backwards and print the character immediately.
public static void main(String[] args) {
String line = "the quick brown fox";
for (char c : line.toUpperCase().toCharArray()) {
if (!Character.isWhitespace(c)) {
System.out.print(c);
}
}
}
You can iterate over character indices in reverse order, convert them to uppercase and remove spaces as follows:
String str = "the quick brown fox";
String reverse = IntStream
// iterate over characters in reverse order
.iterate(str.length() - 1, i -> i >= 0, i -> i - 1)
// take a character by its index
.mapToObj(str::charAt)
// filter only letters
.filter(Character::isLetter)
// character to uppercase
.map(Character::toUpperCase)
// Stream<String>
.map(String::valueOf)
// concatenate into one line
.collect(Collectors.joining());
// output
System.out.println(reverse); // XOFNWORBKCIUQEHT
If the sequence of actions does not matter, then you can first change this string to uppercase, then stream over the character codepoins and filter out whitespaces, and then concatenate back the remaining characters in reverse order:
String line = "the quick brown fox";
String reverse = line
// upper case String
.toUpperCase()
// IntStream over the character code points
.codePoints()
// filter out the space characters
.filter(ch -> !Character.isSpaceChar(ch))
// Stream<String>
.mapToObj(Character::toString)
// concatenate characters in reverse order
.reduce((a, b) -> b + a)
.orElse(null);
System.out.println(reverse); // XOFNWORBKCIUQEHT

How to find the last word in a string

I'm trying to create a method that returns the last word in a string but I am having some trouble writing it.
I am trying to do it by finding the last blank space in the string and using a substring to find the word. This is what I have so far:
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
I am just beginning in Java so I don't know many of the complicated parts of the language. It would be much appreciated if someone could help me find a simple way to solve this problem. Thanks!
You can do this:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
and you've got your last word.
You are splitting the original string at every space and storing the substrings in an array using the String#split method.
Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).
String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
Output:
Wines
String#lastIndexOf and String#substring are your friends here.
chars in Java can be directly converted to ints, which we'll use to find the last space. Then we'll simply substring from there.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
This prints the space character itself too. To get rid of that, we just increment the index at which we substring by one.
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
If you don't want to use String#lastIndexOf, you can loop through the string and substring it at every space until you don't have any left.
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);
You can use: (if you are not familiar with arrays or unusual methods)
public static String lastWord(String a) // only use static if it's in the
main class
{
String lastWord = "";
// below is a new String which is the String without spaces at the ends
String x = a.trim();
for (int i=0; i< x.length(); i++)
{
if (x.charAt(i)==' ')
lastWord = x.substring(i);
}
return lastWord;
}
you just need to traverse the input string from tail when first find blank char stop traverse work and return the word.a simple code like this:
public static String lastWord(String inputs) {
boolean beforWords = false;
StringBuilder sb = new StringBuilder();
for (int i = inputs.length() - 1; i >= 0; i--) {
if (inputs.charAt(i) != ' ') {
sb.append(inputs.charAt(i));
beforWords = true;
} else if (beforWords){
break;
}
}
return sb.reverse().toString();
}
You could try:
System.out.println("Last word of the sentence is : " + string.substring (string.lastIndexOf (' '), string.length()));

Remove letter “e” in the end of each word Java

Need help. Remove letter “e” in the end of each word if word length > 1.
I have tried to do it via strig split and toCharArray, but I can't convert array after removing to string.
Thank you in advance.
public class RemoveE {
public static void main(String args[]) {
String str = "like row lounge dude top";
String[] words = str.split("\\s|[,.;:]");
for (String subStr : words) {
if (subStr.endsWith("e"))
subStr = subStr.substring(0, subStr.length() - 1);
String finalString = new String(subStr);
System.out.println(finalString);
}
}
}
It would be much simpler if you do it via regex like this
finalString = str.replaceAll("e\\b", "");
This is giving following output:
lik row loung dud top
PS: This solution assumes that you would like to drop even a single e in string since in the question, we're using if (subStr.endsWith("e")) which will also remove a single e in the String.
For your code, all the splitting and if conditions are right, all you need to do is add the subStr to finalString when process is completed. I've re-arranged 3 lines from your code, you can find explanation within comments:
public class RemoveE {
public static void main(String args[]) {
String str = "like row lounge dude top";
String[] words = str.split("\\s|[,.;:]");
String finalString = ""; // Bring the declaration outside of for loop
for (String subStr : words) {
if (subStr.endsWith("e"))
subStr = subStr.substring(0, subStr.length() - 1);
finalString += subStr + " "; // Add the substring and a whitespace to substring and add it to finalString to create the sentence again
}
System.out.println(finalString); // Print the String outside of final `for` loop
}
}
This gives the following output:
lik row loung dud top
Raman's first answer provides a good start for a solution with a regular expression. However to ensure that that it only drops the e if the word itself has more than one character, you can add a negative lookbehind to ensure that there is no word boundary immediately before the letter e with (?<!\\b) :
String str = "like row lounge dude top e";
String replaced = str.replaceAll("(?<!\\b)e\\b", "");
System.out.println("Replaced: " + replaced);
This solution is without regex. Adding this as reference as this may be helpful too in future.
I guess, explanation is not needed as a new char array is created and simple for-loop is used to iterate through the input string and keep the valid char in the new char array in appropriate position by checking the conditions.
public class RemoveE {
public static void main (String[] args) {
String str = "like row lounge dude top";
char[] strChars = str.toCharArray();
int size = str.length();
int temp = 0;
char[] newStringChars = new char[size];
String newString = null;
newStringChars[0] = strChars[0];
for(int i=1; i<size; i++) {
if(!(strChars[i] == 'e' && strChars[i+1] == ' ')) {
temp++;
newStringChars[temp] = strChars[i];
}
else if(strChars[i] == 'e' && strChars[i+1] == ' ' && strChars[i-1] == ' ') {
temp++;
newStringChars[temp] = strChars[i];
}
else {
continue;
}
}
newString = String.valueOf(newStringChars);
System.out.println(newString);
}
}
For String str = "like row lounge dude top"; output is:
lik row loung dud top
AND
For String str = "like row e lounge dude top"; (only one e present
in a word, i.e. not word length > 1 as mentioned in the question),
output is:
lik row e loung dud top

Java, split string by punctuation sign, process string, add punctuation signs back to string

I have string like this:
Some text, with punctuation sign!
I am splitting it by punctuation signs, using str.split("regex"). Then I process each element (switch characters) in the received array, after splitting.
And I want to add all punctuation signs back to their places. So result should be like this:
Smoe txet, wtih pinctuatuon sgin!
What is the best approach to do that?
How about doing the whole thing in one tiny line?
str = str.replaceAll("(?<=\\b\\w)(.)(.)", "$2$1");
Some test code:
String str = "Some text, with punctuation sign!";
System.out.println(str.replaceAll("(?<=\\b\\w)(.)(.)", "$2$1"));
Output:
Smoe txet, wtih pnuctuation sgin!
Since you aren't adding or removing characters, you may as well just use String.toCharArray():
char[] cs = str.toCharArray();
for (int i = 0; i < cs.length; ) {
while (i < cs.length() && !Character.isLetter(cs[i])) ++i;
int start = i;
while (i < cs.length() && Character.isLetter(cs[i])) ++i;
process(cs, start, i);
}
String result = new String(cs);
where process(char[], int startInclusive, int endExclusive) is a method which jumbles the letters in the array between the indexes.
I'd read through the string character by character.
If the character is punctuation append it to a StringBuilder
If the character is not punctuation keep reading characters until you reach a punctuation character, then process that word and append it to the StringBuilder.
Then skip to that next punctuation character.
This prints, rather than appends to a StringBuilder, but you get the idea:
String sentence = "This is a test, message!";
for (int i = 0; i<sentence.length(); i++) {
if (Character.isLetter(sentence.charAt(i))) {
String tmp = "" +sentence.charAt(i);
while (Character.isLetter(sentence.charAt(i+1)) && i<sentence.length()) {
i++;
tmp += sentence.charAt(i);
}
System.out.print(switchChars(tmp));
} else {
System.out.print(sentence.charAt(i));
}
}
System.out.println();
You can use:
String[] parts = str.split(",");
// processing parts
String str2 = String.join(",", parts);

Making first letter capital using regex like in ucwords

I need to convert a String value in to Upper case (First letter to upper in every word).
This can be done in php by using ucwords() method.
Ex :
String myString = “HI GUYS”;
myString = myString. toLowerCase().replaceAll(“Regex”, “Some Charactor”)
Thanks with hi5
Using regex, it will be difficult. Try following simple code:
String str="hello world";
String[] words=str.split(" ");
for (String word : words) {
char upCase=Character.toUpperCase(word.charAt(0));
System.out.print(new StringBuilder(word.substring(1)).insert(0, upCase));
}
Output:
Hello World
Undermentioned will work great in all your situation
If you need to get first letter of all words capital ..
-----------------------------------------------------
public String toTheUpperCase(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();
}
When you need first letter of first word to be capitalized
-------------------------------------------------------------
public String toTheUpperCaseSingle(String givenString) {
String example = givenString;
example = example.substring(0, 1).toUpperCase()
+ example.substring(1, example.length());
System.out.println(example);
return example;
}
How to use :: Try defining this code n your super class ( Best code practice )
Now when u need to use this method .. just pass String which you need to transform .
For Ex:: Let us assume our super class as CommanUtilityClass.java ...
Now you need this method in some activity say " MainActivity.java "
Now create object of super class as :: [ CommanUtilityClass cuc; ]
Final task -- use this method as described below:
your_text_view.setText(cuc.toTheUpperCase(user_name)); // for all words
your_text_view.setText(cuc.toTheUpperCaseSingle(user_name)); // for only first word ...
Let me know if you need more details for that ..
Enjoy
Cheers !
System.out.println(ucWord("the codes are better than words !!"));// in main method
private static String ucWord(String word) {
word = word.toLowerCase();
char[] c = word.toCharArray();
c[0] = Character.toUpperCase(c[0]);
int len = c.length;
for (int i = 1; i < len; i++) {
if (c[i] == ' ') {
i++;
c[i] = Character.toUpperCase(c[i]);
}
}
return String.valueOf(c);
}
You can use WordUtils from apache for same purpose,
WordUtils.capitalizeFully(Input String);
Here are simplified versions of the toUpperCase methods.
Change all first letters in the sentence to upper case.
public static String ucwords(String sentence) {
StringBuffer sb = new StringBuffer();
for (CharSequence word: sentence.split(" "))
sb.append(Character.toUpperCase(word.charAt(0))).append(word.subSequence(1, word.length())).append(" ");
return sb.toString().trim();
}
Change only the first word to upper case. (nice one-liner)
public static String ucFirstWord(String sentence) {
return String.valueOf(Character.toUpperCase(word.charAt(0))).concat(word.substring(1));
}
String stringToSearch = "this string is needed to be first letter uppercased for each word";
// First letter upper case using regex
Pattern firstLetterPtn = Pattern.compile("(\\b[a-z]{1})+");
Matcher m = firstLetterPtn.matcher(stringToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,m.group().toUpperCase());
}
m.appendTail(sb);
stringToSearch = sb.toString();
sb.setLength(0);
System.out.println(stringToSearch);
output:
This String Is Needed To Be First Letter Uppercased For Each Word

Categories