Skip to content
Advertisement

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

Advertisement

Answer

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 !

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement