Detect Capital in String | String Problem
4 years ago Lalit Bhagtani 0
Problem Statement
You have given a word, find out if the usage of capital letters in the given word is correct or not.
Correct Usage of capital letters are defined as:-
- Word contains all capital letters like, “HELLO”
- Word contains no capital letters like, “hello”
- Only the first letter of the word is a capital, like “Hello”
Example
Input :- "HELLO" Output :- true
Input :- "MorninG" Output :- false
Solution
This problem can be solved in following steps :-
- If the input string is null or empty, then return false as an output otherwise moves to the next step.
- If the length of the input string is 1, then return true as an output otherwise moves to the next step.
- Create an array of characters from the input string.
- Check if the first two letters of the character array are capital or not, say the result of this step is isSmall.
- Traverse the character array from a second letter (index 1) to end (n-1, where n is the length of an array) and if isSmall is false, then all the letters should be capital and if isSmall is true, then all the letters should not be capitals.
Program
public class Main { public static void main(String[] args) { Main main = new Main(); boolean result = main.detectCapitalUse("MorninG"); System.out.print(result); } /* Solution */ public boolean detectCapitalUse(String word) { if(word == null || word.length() == 0) return false; if(word.length() == 1) return true; char[] array = word.toCharArray(); boolean isSmall = true; if(array[0] >='A' && array[0] <='Z'){ if(array[1] >='A' && array[1] <='Z'){ isSmall = false; } } for(int i=1; i<array.length; i++){ if(isSmall){ if(array[i] >='A' && array[i] <='Z'){ return false; } }else { if(array[i] >='a' && array[i] <='z'){ return false; } } } return true; } }
Result
false
Similar Post
- Split String into Balanced Strings
- Check If Word Is Valid After Substitutions
- Robot Return to Origin
That’s all for Detect Capital in String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.