CS156

CS156: Intro to C, Part I

Fall 2017

Strings

See this page as a slide show

CS156 Strings: Strings

Characters in C

Strings in C

char state[6];
state[0] = 'T'; state[3] = 'a';
state[1] = 'e'; state[4] = 's';
state[2] = 'x'; state[5] = '\0';

    ┌────┬────┬────┬────┬────┬────┐
    │ T  │ e  │ x  │ a  │ s  │ \0 │
    └────┴────┴────┴────┴────┴────┘
      0    1    2    3    4    5

Don’t forget the null character

    char name[7];
    name[0] = 'F'; name[1] = 'o'; name[2] = 'o';
    printf("%s\n", name);

    ┌───┬───┬───┬───┬───┬───┬───┐
    │ F │ o │ o │ ¥ │ ¶ │ € │ ☃ │
    └───┴───┴───┴───┴───┴───┴───┘
      0   1   2   3   4   5   6

Assigning Strings to Variables

    char sam1[4] = {'s','a','m','\0'};
    char sam2[4] = "sam";
    char sam3[] = "sam";
    char name[4];
    strcpy(name, "sam");  // 's', 'a', 'm', '\0'

Assigning Strings to Variables

    // These all do the same thing:
    char name1[5] = "Zulu";
    char name2[] = "Zulu";
    char name3[5] = { 'Z', 'u', 'l', 'u', '\0' };
    char name4[] = { 'Z', 'u', 'l', 'u', '\0' };

    ┌────┬────┬────┬────┬────┐
    │ Z  │ u  │ l  │ u  │ \0 │
    └────┴────┴────┴────┴────┘
      0    1    2    3    4

    /* This one has extra space for growth */
    char name5[10] = { 'Z', 'u', 'l', 'u', '\0' };

    ┌────┬────┬────┬────┬────┬────┬────┬────┬────┬────┐
    │ Z  │ u  │ l  │ u  │ \0 │ ?? │ ?? │ ?? │ ?? │ ?? │
    └────┴────┴────┴────┴────┴────┴────┴────┴────┴────┘
      0    1    2    3    4    5    6    7    8    9    

The C String Library

strlen and the length of strings

A String Mystery

char alpha[] = "123";
char beta[16] = "1234567890abcdef";
char gamma[] = "12345678";
printf("%zd %zd %zd\n", sizeof(alpha), sizeof(beta), sizeof(gamma));
printf("%zd %zd %zd\n", strlen(alpha), strlen(beta), strlen(gamma));
4 16 9
3 19 8

strcat: Concatenating Strings

    char name[12];
    strcpy(name, "Sue");       // name = "Sue", length=3
    strcat(name, " Storm");    // name = "Sue Storm", length=9
    strcat(name, " Richards"); // Runtime failure: too long
    strcat("Ben", "Grimm");    // Compile-time failure
    char buf[10];
    strcat(buf, "xyz");        // Adding on to the end of … what?

strcmp: Comparing Strings

    if (strcmp(string1, string2) == 0)
        printf("The strings are equal.\n");
    if (strcmp(string1, string2))	 // Bad code!  Bad!
        printf("They're the same.\n");   // Liar!

strcmp: Comparing Strings

int strcmp(const char s1[], const char s2[]);

Return value indicates the lexicographical relation of string1 to string2:

Relationship of s1 to s2Value
s1 less than s2some number <0
s1 identical to s2 0
s1 greater than s2some number >0

Vague, isn’t it?

String Use Tips

Modified: 2016-07-30T17:29

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building