Programming Fundamentals/Strings/C: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 23:12, 25 February 2017

arrays.c

// This program splits a given comma-separated name into first and last name
// components and then displays the name.

#include "stdio.h"
#include "string.h"

int find(char text[], char substring[]);
char * ltrim(char text[]);

int main()
{
    char name[256];
    char last[256];
    char first[256];
    int index;

    printf("Enter name (last, first):\n");
    fgets(name, sizeof(name), stdin);
    
    index = find(name, "\n");
    name[index] = '\0';
    
    index = find(name, ",");
    if(index < 0)
    {
        printf("You must enter name in the format: last, first");
    }
    else
    {
        memset(last, 0, sizeof(last));
        strncpy(last, name, index);            
        memset(first, 0, sizeof(last));
        strncpy(first, name + index + 1, strlen(name) - index - 1);
        ltrim(first);
        printf("Hello %s %s!", first, last);
    }
}

int find(char text[], char substring[])
{
    char* location;
    int result;
    
    location = strstr(text, substring);
    if(location == NULL)
    {
        result = -1;
    }
    else
    {
        result = location - text;
    }
    
    return result;
}

char * ltrim(char text[])
{
    int index;
    
    index = 0;
    while(text[index] == ' ')
    {
        index++;
    }
    
    if(index > 0)
    {
        strcpy(text, text + index);
    }
    
    return text;
}

Try It

Copy

See Also