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
Related
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(" "));
I have the following program and I am trying to replace the space in the character array with "%20".
For example, if I have this ['a','b',' '], the output would be this ['a','b','%20'].
This is the program:
import java.util.*;
import java.util.Scanner;
class some_str
{ String str1;
String space_method(String str)
{
char[] chars = str.toCharArray();
//char[] s3=new char[chars.length];
for(char c:chars)
//for (int i=0;i<chars.length;i++)
if(Character.isWhitespace(c))
{
//over here I need to replace the space with '%20'
}
return "\n"+str;
}
}
public class space_str
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter string");
String str= sc.nextLine();
some_str st=new some_str();
System.out.println(st.space_method(str));
}
}
Please help, thanks.
Try this:-
str.replace(" ", "%20");
This method replace all spaces with %20 substring and not char because %20 is not a char.
This is what you want:
String replaceSpace(String string) {
StringBuilder sb = new StringBuilder();
for(char c : string.toCharArray()) {
if (c == ' ') {
sb.append("%20");
} else {
sb.append(c);
}
}
return sb.toString();
}
Note that you can't put "%20" into a char, because it is 3 symbols, not 1. That's why you shouldn't use arrays for this purpose.
With library functions you can use either string.replace(" ", "%20") or string.replaceAll(" ", "%20").
We know that Strings are immutable so to replace all the space characters with the %20 in our string, we can either first convert our String to the array of characters which is what you did and manipulate or we can use StringBuilder class, which you can think of as a mutable string but it is basically an array of chars internally. (There is also StringBuffer which essentially does the same thing as StringBuilder except it is thread safe).
Anyways, this following program does what you need to do.
public String spaceMethod(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (Character.isWhitespace(str.charAt(i))) {
sb.append("%20");
}
else
{
sb.append(str.charAt(i));
}
}
return sb.toString();
}
Regarding the error in your code, the answer by Wow has already explained it. Good luck!
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
Trying to solve a leetcode problem of "valid palindrome" below is the code . when I convert the stringbuffer to string and to lower case the string is getting printed as all lower case letters, but when I access it for comparisons using s.charAt(i), I am getting the uppercase letters as well.
public static void main(String []args){
String s = "aA";
String[] strings = s.split("[^A-Za-z0-9]");
StringBuffer sb = new StringBuffer();
for(int i =0; i<strings.length;i++){
sb.append(strings[i]);
}
String newString = sb.toString().toLowerCase();
System.out.println("New String "+newString);***// output : aa(lower case)***
for(int i =0; i<newString.length()/2;i++){
if(s.charAt(i) != s.charAt(newString.length()-i-1)){
System.out.println(s.charAt(i));//**output 'a**
System.out.println(s.charAt(newString.length()-i-1));//***output 'A'***
}
}
Can someone please explain why?
You are not modifying s, the lower case string is in newString. You need to replace the variable inside the second for:
for(int i =0; i<newString.length()/2;i++){
if(newString.charAt(i) != newString.charAt(newString.length()-i-1)){
System.out.println(s.charAt(i));//**output 'a**
System.out.println(s.charAt(newString.length()-i-1));//***output 'A'***
}
}
If you are willing to get lowercase then use newString variable instead of String s;
for(int i =0; i<newString.length()/2;i++){
if(newString.charAt(i) != newString.charAt(newString.length()-i-1)){
System.out.println(newString.charAt(i));
System.out.println(newString.charAt(newString.length()-i-1));
}
}
If you are planning to check the palindrome or not then the following can be one solution.
String s = "aA";
StringBuffer stringBuffer = new StringBuffer(s);
String reverse = stringBuffer.reverse().toString().toLowerCase();
if (reverse.equals(s.toLowerCase())) {
System.out.println("Palindrome");
} else {
System.out.println("Not palindrome");
}
I am attempting to split a word from its punctuation:
So for example if the word is "Hello?". I want to store "Hello" in one variable and the "?" in another variable.
Here is my code so far:
String inWord = "hello?";
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
String word = parts[0];
String punctuation = parts[1];
} else {
String word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
My problem is that I am getting error: cannot find symbol when I try and print out the word and the punctuation.
Thanks for help in advance
There are other things wrong with your code but your question was why you get the 'cannot find symbol' error.
String inWord = "hello?";
String word;
String punctuation = null;
if (inWord.contains(","+"?"+"."+"!"+";")) {
String parts[] = inWord.split("\\," + "\\?" + "\\." + "\\!" + "\\;");
word = parts[0];
punctuation = parts[1];
} else {
word = inWord;
}
System.out.println(word);
System.out.println(punctuation);
The scope of a variable declaration like String word = ... is only the block (the pieces of code inside '{' and '}') that it's in. The variables word and punctuation don't exist in the scope in which you try to print them.
You need to declare your variables word and punctuation in the same scope (or an enclosing scope) of where you access them in your System.out.println
You made the following errors in your code.
1.Declare the string outside the if condition
2.inWord.contains(","+"?"+"."+"!"+";") this is equal to inword.contains(",?.!;") , so the condition will fail always and it goes to else condition
split() will not store the value based on which you split the string
eg
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
In this the value "-" can't be stored.Hope you understand what i'm trying to convey.
You could try with your custom contains function and StringTokenizer
as:
public class Test{
public static void main(String[] args) {
String inWord = "hello";
String[] wordAndPunctuation = null;
char[] punctuations =new char[]{',','?','.','!',';'};
StringTokenizer tokenizer = new StringTokenizer(inWord,new String(punctuations),true);
int i = 0;
if (Test.contains(inWord,punctuations)) {
while(tokenizer.hasMoreTokens()){
wordAndPunctuation = new String[tokenizer.countTokens()];
System.out.println(tokenizer.countTokens());
wordAndPunctuation[i] = tokenizer.nextToken();
i++;
}
}else{
System.out.println("No punctuation in "+inWord);
}
}
public static boolean contains(String str, char[] charArr){
System.out.println(Arrays.toString(charArr));
for(char c:charArr){
if(str.contains(String.valueOf(c)))
return true;
}
return false;
}
}
I would recommend parsing through the String and checking if the character is a punctuation method:
String sentence = "Hello? Is this Mrs. Doubtfire?"; // Example.
ArrayList<String> chunks = new ArrayList<>(); // Will store the "non-punctuated chunks"
ArrayList<Character> puncts = new ArrayList<>();// Will the punctuations in the "sentence"
char[] punctuations = {',','?','.','!',';'}; // Store punctuations here.
int lastIndex = 0;
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
for (char punctuation : punctuations) {
if (c == punctuation) {
chunks.add(sentence.substring(lastIndex, i).trim());
puncts.add(c);
lastIndex = i + 1;
}
}
}
System.out.println(chunks);
System.out.println(puncts);
Output:
[Hello, Is this Mrs, Doubtfire]
[?, ., ?]
And remember to import java.util.ArrayList!
Why don't you do this:
String s = "hello!";
Pattern p = Pattern.compile("(\\w+)?(\\W)");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println("Word: " + m.group(1) + " | Punctuation: " + m.group(2));
}
Group1 will contain the word and Group2 will contain the punctuation.
Demo : http://ideone.com/ljIZFW