Question

I would like to create a method that can cut the word variable and put each letter in the array tab[].

Here is my effort.

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);        
    }
}
Was it helpful?

Solution

To split your word or mot variable, simply use String#toCharArray

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

This will let you navigate the string per-character using an int index.

I'm not entirely certain how you want to assign the word to the tab[] table however, seeing as it is a String type but it seems you want characters in it. If you want tab[] to simply be the characters in the string, then just assign it accordingly with the return value of toCharArray

If they absolutely must be strings, then you can just translate it to a String array of characters:

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

OTHER TIPS

If I understood it correctly, you want to retrieve each character and store it in the Array of Strings tab[].

You could try this method.

public void separate_each () {
  int length = mot.length();
  tab = new String[length];
  for (int index = 0; index < length; index++)
    tab[index] = mot.charAt(index) + "";
}

Hope it helps ^^

I would declare tab as an array of chars:

private char[] tab;

you could then split the word like this:

tab = mot.toCharArray();

a char can always be converted into a String when needed:

String s = Character.toString(ch);
public static void main(String arg[])
    {
        String [] test="789455555".split("");
        for(String s:test)
            System.out.println(s);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top