我正在尝试使用以下代码,以便给定一个字符串,给出相同字符的最长连续子序列的长度。我收到错误“不兼容的类型:char 无法转换为 java.lang.String”。我在下面评论了发现错误的地方。
public class Test {
public int longestRep(String str)
{
int currLen = 1;
String currLet = "";
String maxLet = "";
int maxCount = 0;
int currPos = 0;
int strLen = str.length();
for(currPos = 0; currPos < strLen; currPos++)
{
currLet = str.charAt(currPos); //error is on this line
if(currLet = str.charAt(currPos+1))
{
currLen++;
}
else
{
if(currLen > maxLen)
{
maxLen = currLen;
maxLet = currLet;
currLen = 1;
}
}
}
}
public static void main(String args[])
{
longestRep("AaaaMmm");
}
}
最佳答案
String.charAt(int)
返回一个字符。但是 currLet
是 String
类型,所以不能给字符赋值。使用 currLet = Character.toString(str.charAt(currPos));
代替。
关于java - 字符错误 "char cannot be converted to string",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270624/