【问题标题】:java split each letter and put it in table [duplicate]java拆分每个字母并将其放入表中[重复]
【发布时间】:2014-06-23 01:55:41
【问题描述】:

我想创建一个可以剪切单词变量并将每个字母放入数组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);        
    }
}

【问题讨论】:

  • 我不知道你的代码是否糟糕,但我完全不知道什么是什么。
  • 我不明白,你能提供示例输入和预期输出吗?
  • 发布一些输入和预期输出
  • 对不起,我表达得很糟糕。我想在一个方法中使用“mot”的值,它会返回一个表格,每个框中都有一个字母。 mot = "托托";标签 [0] = "t" 标签 [1] = "o" 标签 [2] = "t" 标签 [3] = "o"

标签: java class methods split


【解决方案1】:

要拆分您的单词或mot 变量,只需使用String#toCharArray

char[] letters = this.mot.toCharArray();

这将允许您使用 int 索引按字符浏览字符串。

我不完全确定您希望如何将单词分配给 tab[] 表,但是,因为它是 String 类型,但您似乎想要其中的字符。如果您希望tab[] 只是字符串中的字符,那么只需将其相应地分配给toCharArray 的返回值

如果它们绝对必须是字符串,那么您可以将其转换为字符串字符数组:

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]);
}

【讨论】:

    【解决方案2】:

    如果我理解正确,您想检索每个字符并将其存储在字符串数组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) + "";
    }
    

    希望对你有帮助^^

    【讨论】:

      【解决方案3】:

      我会将 tab 声明为一个字符数组:

      private char[] tab;
      

      然后你可以这样拆分单词:

      tab = mot.toCharArray();
      

      char 总是可以在需要时转换为 String:

      String s = Character.toString(ch);
      

      【讨论】:

        【解决方案4】:
        public static void main(String arg[])
            {
                String [] test="789455555".split("");
                for(String s:test)
                    System.out.println(s);
            }
        

        【讨论】:

          猜你喜欢
          • 2010-12-04
          • 1970-01-01
          • 1970-01-01
          • 2020-08-26
          • 2015-01-07
          • 2019-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-17
          相关资源
          最近更新 更多