Java 返回大写字母s或-1(如果未找到)
所以,在这个java程序中。。。我正试图返回字符串中的最后一个字母。 关键是字符串可以以字母或数字结尾。我该怎么做呢? 另外,如果没有找到信件,我被指示返回-1Java 返回大写字母s或-1(如果未找到),java,string,Java,String,所以,在这个java程序中。。。我正试图返回字符串中的最后一个字母。 关键是字符串可以以字母或数字结尾。我该怎么做呢? 另外,如果没有找到信件,我被指示返回-1 public static int lastElement(String s) { for (int i = s.length(); i >= 0; i--){ int lastElement = s.indexOf(i); char y = s.charAt(i); if
public static int lastElement(String s) {
for (int i = s.length(); i >= 0; i--){
int lastElement = s.indexOf(i);
char y = s.charAt(i);
if (Character.isDigit(y)){
i--;
}
else{
return lastElement;
}
}
return -1;
}
请在线查看我的评论
public static int lastElement(String s) {
// the last index is length - 1
for (int i = s.length() - 1; i >= 0; i--) {
// get the character at an index, rather than search for the index
char ch = s.charAt(i);
// if it's not a digit
if (!Character.isDigit(ch))
// return it as an upper case letter.
return Character.toUpperCase(ch);
// if it is a digit, you don't need to do anything
// as it will go onto the next index anyway.
}
return -1;
}
注意:您可能希望使用
if(Character.isDigit(ch))
更改if(!Character.isDigit(ch))
这是因为有许多字符,例如空格,它们既不是数字,也不是字母。请参阅我的在线评论
public static int lastElement(String s) {
// the last index is length - 1
for (int i = s.length() - 1; i >= 0; i--) {
// get the character at an index, rather than search for the index
char ch = s.charAt(i);
// if it's not a digit
if (!Character.isDigit(ch))
// return it as an upper case letter.
return Character.toUpperCase(ch);
// if it is a digit, you don't need to do anything
// as it will go onto the next index anyway.
}
return -1;
}
注意:您可能希望使用
if(Character.isDigit(ch))
更改if(!Character.isDigit(ch))
这是因为有许多字符(例如空格)不是数字,它们也不是字母。使用continue
而不是i--
,如果要返回最后一个字符,而不是最后一个字符的索引,则可能需要返回y
。字符串的第一个字符位于索引0处。所以最后一个是索引length-1
,而不是length
。此外,还有字母、数字和其他类型的字符。不是数字的字符不一定是字母。不清楚为什么要使用indexOf
。。。你为什么不直接返回i
?你还应该澄清一下:你需要返回最后一个字母(即y
),还是最后一个字母的索引(即i
)?真不敢相信我在帮萨拉·佩林!接下来呢?唐纳德·特朗普?我太好了。使用continue
而不是I--
,如果要返回最后一个字符,而不是最后一个字符的索引,则可能需要返回y
。字符串的第一个字符位于索引0处。所以最后一个是索引length-1
,而不是length
。此外,还有字母、数字和其他类型的字符。不是数字的字符不一定是字母。不清楚为什么要使用indexOf
。。。你为什么不直接返回i
?你还应该澄清一下:你需要返回最后一个字母(即y
),还是最后一个字母的索引(即i
)?真不敢相信我在帮萨拉·佩林!接下来呢?唐纳德·特朗普?我太好了。@JBNizet我加了一个注释来说明这一点。我不清楚OP在这方面想要什么。@JBNizet我为此添加了一个注释。我不清楚OP在这方面想要什么。