在a-z的alphabet中去掉用户输入的keyword,以zebra举例,去掉之后的alphabet应该是cdfghijklmnopqtuvwxy。我的代码是这样的:
private String removeKeyword(String modifiedKeyword){
int i = 0;
String removeKeyword = "abcdefghigklmnopqrstuvwxyz";
while (i < 26 ){
if(modifiedKeyword.indexOf(removeKeyword.charAt(i)) != -1){
removeKeyword = removeKeyword.replace("" + removeKeyword.charAt(i), "");
}
i++;
}
return removeKeyword;
}
compile没有问题,但是运行之后生成的新字母列是zebrasbcdefghigklmnopqrstuvwxyz,也就是说只去掉了a然后替换了zebras,到底问题出在哪。。。
private String removeKeyword(String modifiedKeyword){
int i;
String removedKeyword = "abcdefghijklmnopqrstuvwxyz";
for ( i = 0 ; modifiedKeyword.indexOf(removedKeyword.charAt(i)) != -1 ; i++){
removedKeyword = removedKeyword.replace("" + PLAIN_ALPHA.charAt(i),"");
}
return removedKeyword;
}
不好意思打错了 ,这个是我运行的代码,上边那个运行之后提示
java.lang.StringIndexOutOfBoundsException: String index out of range: 23
字符串中去掉指定的字符
答案:2 悬赏:30
解决时间 2021-04-21 14:18
- 提问者网友:霸气大叔
- 2021-04-20 14:19
最佳答案
- 二级知识专家网友:不服输就别哭
- 2021-04-20 15:42
是不是用了string.indexOf,这个的话,表示越界了,你的字符串没这么大的长度.
给你举一个简单的例子,讲解方法indexOf(int ch)
源文件Test.java
public class Test {
public static void main(String args[])
{
String str1="aacdabcd";
String str2="abcdabcd";
System.out.println(str1.indexOf(98));
System.out.println(str2.indexOf(98));
}
}
运行结果是5和1。
indexOf(int ch)方法的作用是字符在此字符串中第一次出现处的索引.。整型(int)数据它会转换成字符型(char),例中的98对应的是字符'b',字符'b'在字符串str1中第一次出现处是第5个位置(不是第6个,因为是从0开始计算的,这个应该知道吧),在字符串str2中第一次出现处是第1个位置。
其实实参98换成'b',运行结果是一样的。换成101则返回-1,101对应的是字符'e',字符串str1,str2中没有字符'e',方法返回的值是-1。.
给你举一个简单的例子,讲解方法indexOf(int ch)
源文件Test.java
public class Test {
public static void main(String args[])
{
String str1="aacdabcd";
String str2="abcdabcd";
System.out.println(str1.indexOf(98));
System.out.println(str2.indexOf(98));
}
}
运行结果是5和1。
indexOf(int ch)方法的作用是字符在此字符串中第一次出现处的索引.。整型(int)数据它会转换成字符型(char),例中的98对应的是字符'b',字符'b'在字符串str1中第一次出现处是第5个位置(不是第6个,因为是从0开始计算的,这个应该知道吧),在字符串str2中第一次出现处是第1个位置。
其实实参98换成'b',运行结果是一样的。换成101则返回-1,101对应的是字符'e',字符串str1,str2中没有字符'e',方法返回的值是-1。.
全部回答
- 1楼网友:狠傷凤凰
- 2021-04-20 16:10
因为你在遍历的过程中对32313133353236313431303231363533e4b893e5b19e31333332633061他有修改,所以导致了这个错误.
char[] removeKeyword = "abcdefghigklmnopqrstuvwxyz".toCharArray();
String removeKeywordStr = "";
for (int i = 0; i < 26; i++) {
for (int j = 0; j < modifiedKeyword.length(); j++) {
if (removeKeyword[i] == modifiedKeyword.charAt(j)) {
removeKeyword[i] = 0;
}
}
}
for (int i = 0; i < 26; i++) {
if (removeKeyword[i] == 0) {
continue;
}
removeKeywordStr += removeKeyword[i];
}
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯