Essential Knowledge Points for C Language Beginners: Summary of Character Arrays and String Usage Techniques

“From today on, study hard and make progress every day”

Repetition is the best method for memory; spend one minute every day to remember the basics of C language.

Essential Knowledge Points for C Language Beginners: 100 Articles Series

The following notes finally enter the practical series, which is also the most important and difficult part of C language. Keep it up, young learners!

34. Summary of Character Arrays and String Usage Techniques in C Language: Thoroughly Understand String Processing!

1. Character Arrays

A character array is the basic data structure for storing characters in C language and can be used to store strings. However, note that the last character must be ‘\0’; otherwise, it is a character array, not a string.

char str[10];  // Can store up to 9 characters + 1 '\0'

String Characteristics

  • • Ends with a null character<span>'\0'</span> (ASCII 0)
  • • Actual length ≤ array length – 1
  • • Stored in contiguous memory

2. String Initialization Methods

1. Character-by-character Initialization

char str1[5] = {'H', 'e', 'l', 'l', 'o'};  // Not a string, just a character array (no '\0')
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'};  // Valid string

2. String Literal Initialization

char str3[6] = "Hello";  // Automatically adds '\0'
char str4[] = "World";   // Automatically calculates length (6)

3. Pointer Initialization

char *str5 = "Hello";  // Stored in read-only data segment

3. String Input and Output

1. Standard Input and Output

char name[20];
printf("Enter name: ");
scanf("%19s", name);  // Limit length to prevent overflow
printf("Hello, %s\n", name);

2. Safe Input Functions

fgets(name, sizeof(name), stdin);  // Includes newline character

3. Character-by-character Processing

int i = 0;
while (str[i] != '\0') {
    putchar(str[i++]);
}

4. String Processing Functions

1. Common Functions in <string.h>

Function Description Example
strlen Calculate string length strlen(“Hello”) → 5
strcpy String copy strcpy(dest, src)
strncpy Safe string copy strncpy(dest, src, n)
strcat String concatenation strcat(s1, s2)
strncat Safe string concatenation strncat(s1, s2, n)
strcmp String comparison strcmp(s1, s2)
strchr Find first occurrence of a character strchr(str, ‘l’)
strstr Find first occurrence of a substring strstr(str, “ll”)

2. Usage Example

char s1[20] = "Hello";
char s2[] = " World";
strcat(s1, s2);  // s1 becomes "Hello World"

5. Strings and Pointers

1. Pointer Traversal of Strings

char *p = "Hello";
while (*p) {
    // Postfix ++ has higher precedence than dereference *, postfix returns original value first, then increments
    putchar(*p++);
}

2. Pointer Array Storing Strings

char *colors[] = {"Red", "Green", "Blue"};
printf("%s", colors[1]);  // Outputs "Green"

6. Common Errors

1. Buffer Overflow

char buf[10];
scanf("%s", buf);  // Dangerous! Input too long will overflow

Limit length:

scanf("%9s", buf);  // Limit length

2. String Not Terminated, Insufficient Space Lacking ‘\0’

char str[5] = "Hello";  // No space for '\0'

Correction:

char str[6] = "Hello";  // Correct

3. Modifying Read-Only Strings

// Strings initialized in pointer form are read-only
char *p = "constant";
*p = 'C';  // Runtime error!

Correction:

char arr[] = "modifiable";
arr[0] = 'M';  // Correct

7. Common Program Examples for Strings

1. String Length Function

size_t my_strlen(const char *s) {
    size_t n = 0;
    while (*s++) n++;
    return n;
}

2. String Reversal Implementation

void reverse(char *str) {
    int i = 0, j = strlen(str)-1;
    while (i < j) {
        char temp = str[i];
        str[i++] = str[j];
        str[j--] = temp;
    }
}

3. Splitting Strings

char str[] = "apple,orange,banana";
char *token = strtok(str, ",");
while (token) {
    printf("%s\n", token);
    // Pass NULL to continue splitting the same string from the last end position
    token = strtok(NULL, ",");
}

Some students contacted me, wanting to have a study exchange group. Previously, I hesitated to create a group due to concerns about advertisements, but considering that having a group is indeed convenient, I will create one this time to try it out.

If you need it, hurry up and join; the validity period is 7 days.

Essential Knowledge Points for C Language Beginners: Summary of Character Arrays and String Usage Techniques

———- End ———-

[Special Statement: All articles in this public account are original or authorized by the author. Some content and images are sourced from the internet. Please feel free to consume them. The views are for learning reference only. If there are any errors or omissions, please forgive me.]

Essential Knowledge Points for C Language Beginners: Summary of Character Arrays and String Usage Techniques

Essential Knowledge Points for C Language Beginners: Summary of Character Arrays and String Usage Techniques

“If you like C, please give a thumbs up”Essential Knowledge Points for C Language Beginners: Summary of Character Arrays and String Usage Techniques Click the bottom right corner to viewEssential Knowledge Points for C Language Beginners: Summary of Character Arrays and String Usage Techniques

Leave a Comment