Programming Fundamentals/Strings/C

From Wikiversity
Jump to navigation Jump to search

strings.c[edit | edit source]

// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Programming

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

void get_name(char name[], int size);
void get_last(char name[], char last[], int size);
void get_first(char name[], char first[], int size);
void display_name(char first[], char last[]);
int find(char text[], char substring[]);
char *ltrim(char text[]);

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

    get_name(name, sizeof(name));
    get_last(name, last, sizeof(last));
    get_first(name, first, sizeof(first));
    display_name(first, last);
}

void get_name(char name[], int size)
{
    int index;

    do
    {
        memset(name, 0, size);
        printf("Enter name (last, first):\n");
        fgets(name, size, stdin);
        
        index = find(name, "\n");
        name[index] = '\0';

        index = find(name, ",");
    } while (index < 0);
}

void get_last(char name[], char last[], int size)
{
    int index;

    memset(last, 0, size);
    index = find(name, ",");
    if(index < 0)
    {
        strcpy(last, "");
    }
    else
    {
        strncpy(last, name, index);
    }
}

void get_first(char name[], char first[], int size)
{
    int index;

    memset(first, 0, size);
    index = find(name, ",");
    if(index < 0)
    {
        strcpy(first, "");
    }
    else
    {
        strncpy(first, name + index + 1, strlen(name) - index - 1);
        ltrim(first);
    }
}

void display_name(char first[], char last[])
{
    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)
    {
        memmove(text, text + index, strlen(text) - index + 1);
    }
    
    return text;
}

Try It[edit | edit source]

Copy

See Also[edit | edit source]