[英]Number of times the last character appears in JAVA only use String
I'm doing a part of a program, where I should see the number of times the last character appears in JAVA.我正在做一个程序的一部分,在那里我应该看到最后一个字符在 JAVA 中出现的次数。
The problem is that I am new with the use of Strings ( and only can use String ).问题是我是使用 Strings 的新手(并且只能使用 String )。 Informing a bit I have seen that with equals I can compare Strings.告知一点我已经看到,我可以用 equals 比较字符串。 And with substring I can select each of the letters one by one in a loop.使用子字符串,我可以在循环中一个一个地选择每个字母。 The problem comes when I compile, that I go out of the index of the String.当我编译时,问题出现了,我超出了字符串的索引。 And I do not understand why, since I only get to .length - 1我不明白为什么,因为我只得到 .length - 1
String aux;
int cont = 0;
aux = cadena.substring(cadena.length()-1);
for (int i = 0; i < cadena.length()-1; i++) {
if(cadena.substring(i,1).equals(aux)) {
cont++;
}
}
java.lang.StringIndexOutOfBoundsException: String index out of range:-1 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1
In this line在这一行
if(cadena.substring(i,1).equals(aux)) if(cadena.substring(i,1).equals(aux))
what you have done is like "Hello".substring(3, 1)
你所做的就像"Hello".substring(3, 1)
substring
method takes two arguments startIndex
and endIndex
. substring
方法采用两个参数startIndex
和endIndex
。 so end index should always be greater than start index.所以结束索引应该总是大于开始索引。
In cadena.substring(i,1)
, the value of i
will go from 0
to cadena.length()-2
, because of condition i<cadena.length()-1
在cadena.substring(i,1)
, i
的值将从0
到cadena.length()-2
,因为条件i<cadena.length()-1
You can do something like this:你可以这样做:
int count = 0;
char lastChar = cadena.charAt(cadena.length()-1);
for (int i = 0; i < cadena.length()-1; i++) {
if(lastChar==cadena.charAt(i)) count++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.