Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
- All letters in this word are capitals, like "USA".
- All letters in this word are not capitals, like "leetcode".
- Only the first letter in this word is capital if it has more than one letter, like "Google".
Example 1:
Input: "USA" Output: True
Example 2:
Input: "FlaG" Output: False
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
public class Solution {
public boolean detectCapitalUse(String word) {
char[] a=word.toCharArray();//使用word.charAt(i) 也可以
int cap=0;
for(int i=0;i<word.length();i++)
{
if(a[i]>='a')cap++;
else {
if(cap>0)return false;
}
}
if(cap<a.length-1&&cap>0)return false;
return true;
}
}
大神的一行代码
return word.toUpperCase().equals(word) || word.substring(1).toLowerCase().equals(word.substring(1));
substring(参数)是java中截取字符串的一个方法
有两种传参方式
一种是public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。
public String substring(int beginIndex)
Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.Examples:
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string)
另一种是public String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。
subString=number.subString(i,i+1);
定义一个String类型的变量去存储number截取第i个位置到第i+1个位置的字符串