Home > Software design >  How can i read the strings(individually) in a single input, that are seperated by white space?
How can i read the strings(individually) in a single input, that are seperated by white space?

Time:12-17

So, if i'am given an input, as follows:

Hello        how   
are   you
doing?  I'm      doing 
fine!      *** 

what can i do to get an output saying :

There are 9 strings:
1. Hello
2. how
3. are
4. you
5. doing?
6. I'm 
7. doing
8. fine!
9. ***

so basically , what i want is to read the strings seperated by white-space individually! Any ideas?

CodePudding user response:

As others have mentioned, use strtok from string.h. It will allow you to pick a delimiter to find substrings by, which in your case is just " ". You can then loop through and find all the substrings delimited by whitespace.

#include <stdio.h>
#include <string.h>

int main() {
    char words[] = "Hello     how  are   you   doing?  ***";
    char *word = strtok(words, " ");

    while (word != NULL) {
        printf("%s\n", word);
        word = strtok(NULL, " ");
    }

    return 0;
}

Output:

Hello
how
are
you
doing?
***

CodePudding user response:

package com.tools;

import java.util.StringTokenizer;

public class StringParser {

public void parse(String str)
{
    StringTokenizer st = new StringTokenizer(str,"\n\r ");
    String token ="";
    int num = 0;
    while (st.hasMoreElements())
    {
        token = st.nextElement().toString();
        if (token.trim().length() > 0)
        {
            System.out.println(  num ". " token);
        }
    }
    
}

public static void main (String a[])
{
    
    StringParser st = new StringParser();
    String str = "Hello        how   \r\n"
              "are   you\r\n"
              "doing?  I'm      doing \r\n"
              "fine!      *** ";

    st.parse(str);
}

}

  • Related