我想创建一个方法,可以剪切单词变量并将每个字母放在数组tab[]
中。
这是我的努力。
public class Mot {
private String mot;
private String tab[];
//getter et setter
public String getMot() {
return mot;
}
public void setMot(String mot) {
this.mot = mot;
}
//constructeur plein
public Mot(String mot, String[] tab) {
this.mot = mot;
this.tab = tab;
}
//constructeur vide
public Mot(){
}
//methodes
public void affichage(){
System.out.println(this.tab[1]);
}
//placage de chaque lettre dans un tableau
public void tableau(){
this.tab = this.mot.split(mot);
}
}
答案 0 :(得分:1)
要拆分您的单词或mot
变量,只需使用String#toCharArray
char[] letters = this.mot.toCharArray();
这将允许您使用int
索引导航每个字符的字符串。
我并不完全确定你想如何将这个词分配到tab[]
表,但是看到它是String
类型,但似乎你想要它中的字符。如果您希望tab[]
只是字符串中的字符,那么只需相应地指定它,返回值为toCharArray
如果它们绝对必须是字符串,那么您只需将其转换为String字符数组:
char[] raw = this.mot.toCharArray();
this.tab = new String[raw.length];
for(int i = 0; i < raw.length; i++) {
this.tab[i] = Character.toString(raw[i]);
}
答案 1 :(得分:0)
如果我理解正确,您需要检索每个字符并将其存储在字符串数组tab[]
中。
你可以尝试这种方法。
public void separate_each () {
int length = mot.length();
tab = new String[length];
for (int index = 0; index < length; index++)
tab[index] = mot.charAt(index) + "";
}
希望它有所帮助^^
答案 2 :(得分:0)
我会将tab声明为chars数组:
private char[] tab;
然后你可以像这样分开这个词:
tab = mot.toCharArray();
在需要时,char总是可以转换为String:
String s = Character.toString(ch);
答案 3 :(得分:0)
public static void main(String arg[])
{
String [] test="789455555".split("");
for(String s:test)
System.out.println(s);
}