Thread: Splitting a String into Separate Characters, or an Array

  1. #1
    Registered User
    Join Date
    Feb 2014
    Posts
    2

    Splitting a String into Separate Characters, or an Array

    I have been looking everywhere, but the only place I have seen it done is Objective C. The Question: how do I split a string, input by the user, into an array of characters? No code shown because I know no commands that do this.


    --Input by user as in fgets, or scanf().
    Last edited by ibigio; 02-18-2014 at 06:53 AM.

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    A C string, by definition, is an array of characters terminated with a null character ('\0'). So to read and save a string, you need a character array to store it in*. Therefore, in response to your question, the work has already been done.

    Code:
    #include <stdio.h>
    
    #define MAX_LEN 64
    
    int main(void)
    {
        char input_string[MAX_LEN];  /* character array to store the string */
        int i;
    
        printf("Enter a string:\n");
        fgets(input_string,sizeof(input_string),stdin);  /* read the string */
    
        /* print the string as a whole */
        printf("\nYour string printed out as a string:\n");
        puts(input_string);
    
        /* print the string by printing each element of the array */
        printf("Your string printed out as individual characters:\n");
        for(i=0; input_string[i] != '\0'; i++)
        {
            putchar(input_string[i]);
        }
    
        return 0;
    }
    This is the answer to the question you asked. If you actually meant something different, please clarify the question.



    * Well, there are other ways, such as saving the string in dynamically allocated memory through a pointer, but using a character array would seem to suit your purposes.
    Last edited by Matticus; 02-18-2014 at 07:24 AM. Reason: added info

  3. #3
    Registered User
    Join Date
    Feb 2014
    Posts
    2
    Thank you! That is exactly what I needed. I hadn't found out about the putchar, but that is precisely it. Now I believe I can edit each character individualy.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Constantly adding characters from an array to a string
    By mconflict in forum C Programming
    Replies: 2
    Last Post: 04-02-2012, 11:38 PM
  2. Splitting string in chunks of 2 characters
    By ScoutDavid in forum C++ Programming
    Replies: 8
    Last Post: 03-27-2011, 05:34 AM
  3. Replies: 6
    Last Post: 02-28-2011, 03:45 PM
  4. Separate long string into multiple arrays
    By cashmerelc in forum C Programming
    Replies: 6
    Last Post: 11-27-2007, 02:57 AM
  5. Can a string be converted to an array of characters?
    By supaben34 in forum C++ Programming
    Replies: 8
    Last Post: 12-08-2002, 12:18 PM

Tags for this Thread