------------------------------------------------------------------------------
MC logo
More C Strings
[^] CSc 220 Home
------------------------------------------------------------------------------
[Introduction] [Boolean and Control] [Functions] [Arrays and Pointers] [Dynamic Arrays] [Array Errors] [Command Array] [Standard Containers] [Structs and Classes] [Automatic Pointer] [Multi-File Programs] [Copying Objects] [Templates] [Inheritance] [Plain C I/O] [Type Odds And Ends] [Plain C Strings] [File I/O]
[C Strings] [More C Strings] [Plain C Arg Lister] [Fancy Plain C Arg Lister (With Pointers)] [Simple String Sort]
str2.c
/*
 * String games using the standard string facility.
 */
#include <stdio.h>
#include <string.h>

int main()
{
        char s1[25] = "This is the city.";
        char s2[50];
        char *p1, *p2;

        /* strcpy copies the second string to the first. */
        strcpy(s2, s1);
        printf("%s %s\n", s1, s2);

        /* Use strcat to add a second string to the first. */
        strcat(s2, "  Los Angeles, California.");
        printf("%s\n", s2);

        /* By fixing up the destination address, we can get strcpy to
           effectively cut off part of the first string. */
        strcpy(s2 + 7, "***");
        printf("%s\n\n", s2);

        /* The strlen function tells how many characters there are in the 
           string. */
        printf("\"%s\" has %d characters, \"%s\" has %d characters.\n\n",
               s1, strlen(s1), s2, strlen(s2));

        /* A strstr and strchr search for a substring or a member character. */
        p1 = strchr(s1, 'c');
        printf("[%c] [%s]\n", *p1, p1);
        p1 = strstr(s1, "the");
        printf("[%c] [%s]\n", *p1, p1);
        p2 = strstr(s1, "nope");
        if(p2 == NULL) printf("No \"nope\"\n");
        putchar('\n');

        /* This doesn't work correctly.  Java actually has a similar problem.
           It's annoying in C, but Java is s'posed to cleanup up stuff like
           that. */
        strcpy(s2, s1);
        printf("%s\n%s\n", s1, s2);
        if(s1 == s2)
                printf("Same.\n");
        else
                printf("Different.\n");

        /* You may use strcmp to compare strings. */
        if(strcmp(s1, s2) == 0)
                printf("Same.\n");
        else
                printf("Different.\n");
}