在字符串中添加字符
我正在尝试制定一种方法来帮助我正确拼写世界。在 addChar
根据输入 "famili"
返回其工作后,我希望结果数组包含单词 "familiy"
。现在该方法从字符串中删除一个字符并将其替换为 alpha[] 中的当前字符,有人可以给我一些帮助,使该方法从 alpha[] 添加字符 位于两个字符之间,而不是删除一个来获取空格。
class Main {
char [] alpha = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'y', 'z'};
public static void main(String [] args) {
Main m = new Main();
String [] result = m.addChar("famil");
}
public String[] addChar(String word) {
String [] words = new String[word.length() * alpha.length];
int k = 0;
for(int i = 0; i < alpha.length; i++) {
for(int j = 0; j < word.length(); j++) {
StringBuffer buf = new StringBuffer(word);
buf.setCharAt(j, alpha[i]);
words[k++] = buf.toString();
}
}
return words;
}
}
I'm trying to make a method that shall help me to spell world right. After addChar
have return its work based on the input "famili"
, I want the result array to contain the word "familiy"
. Now the method removes a character from the string and replace it with the current char in alpha[]
, can someone please give me some help to make this method to add the char from alpha[]
between two characters and not delete one to get space.
class Main {
char [] alpha = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'y', 'z'};
public static void main(String [] args) {
Main m = new Main();
String [] result = m.addChar("famil");
}
public String[] addChar(String word) {
String [] words = new String[word.length() * alpha.length];
int k = 0;
for(int i = 0; i < alpha.length; i++) {
for(int j = 0; j < word.length(); j++) {
StringBuffer buf = new StringBuffer(word);
buf.setCharAt(j, alpha[i]);
words[k++] = buf.toString();
}
}
return words;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 StringBuffer 类的“nofollow">插入 方法代替
setCharAt
。工作链接
You can make use of the insert method of the
StringBuffer
class in place ofsetCharAt
.Working link
我大概会这样解决。
I would probably solve it like this.
尝试使用 LinkedList。
Try to use LinkedList.