How to split a list of words into individual words, then into letters?

edited October 2013 in How To...

I'm trying to split a list of words into separate words, then into individual letters. e.g. from "dog cat ball" into "dog" "cat" "ball" into "d" "o" "g" "c" "a" "t" "b" "a" "l" "l"

I currently have:

String wordList = "laugh fly cold drink jump";
String [] word = split(wordList, " ");

int letters;

for (int i = 0; i < word.length; i++) {
  letters = Integer.parseInt(word[i]);

but it's not doing anything, really.

I'm totally new to processing and don't have a clear understanding on how to use strings and split and parseInt and all that.

Any help is appreciated!

Answers

  • edited October 2013

    Here you go:

       String original="Simple Tutorial To Split Words";
        String[] splited=original.split(" ");//Split by space the original string
        char[] letters;
    
        for(int i=0; i<splited.length;i++)
        {
            System.out.println("Word "+i+": "+splited[i]);//access each word resultant of the split operation
            System.out.println("METHOD 1");
            for(int j=0;j<splited[i].length();j++)
            {
                System.out.println("Letter "+j+": "+splited[i].charAt(j));//you can access each letter with this methos
            }
            System.out.println("METHOD 2");
            letters=splited[i].toCharArray();//convert a word to a char array, so you can access
            for(int j=0;j<splited[i].length();j++)
            {
                System.out.println("Letter "+j+": "+letters[j]);//or you can access each letter wit this method
            }
            System.out.println("");
        }
    
  • _vk_vk
    edited October 2013

    [edit] ops late:)

    [edit2] if this is going to go huge, you might want to use StringBuilder() as its is faster.

    Something like this?

    String wordList = "laugh fly cold drink jump";
    
    void setup() {
      String [] words = split(wordList, " ");
    
      // prints to console
      println(words);
    
      //temp string without spaces
      String noSpaces = "";
      for (String s : words) {
        noSpaces += s;
      }
    
      char[] letters = noSpaces.toCharArray();  
    
      println(letters);
    }
    
Sign In or Register to comment.