Tutorials Logic, IN info@tutorialslogic.com

C Strings strlen, strcpy, strcat, strcmp: Tutorial, Examples, FAQs & Interview Tips

C Strings strlen, strcpy, strcat, strcmp

C in C is best learned by connecting the rule to a small command-line program. Start with the smallest function, observe the output, and then add one realistic constraint so the concept becomes practical.

The key habit for this lesson is to watch pointer, array, or file buffer as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.

What is a String in C?

In C, a string is an array of characters terminated by a null character '\0'. There is no built-in string type - strings are always char arrays.

What is a String in C?

What is a String in C?
// String declaration and initialization
char name[10] = "Alice";    // stored as: A l i c e \0 _ _ _ _
char name[] = "Alice";      // size inferred: 6 bytes (5 chars + \0)
char name[] = {'A','l','i','c','e','\0'};  // explicit null terminator

// String literal (read-only pointer)
char *msg = "Hello";        // pointer to string literal

string.h Functions

The <string.h> header provides many useful string manipulation functions:

Function Description Example
strlen(s) Returns length of string (excluding \0) strlen("hello") -> 5
strcpy(dest, src) Copies src into dest strcpy(a, "hi")
strncpy(dest, src, n) Copies at most n characters Safer version of strcpy
strcat(dest, src) Appends src to end of dest strcat(a, " world")
strncat(dest, src, n) Appends at most n characters Safer version of strcat
strcmp(s1, s2) Compares two strings; 0 if equal strcmp("abc","abc") -> 0
strncmp(s1, s2, n) Compares first n characters Safer version of strcmp
strchr(s, c) Finds first occurrence of char c strchr("hello",'l')
strstr(s, sub) Finds first occurrence of substring strstr("hello","ell")
strtok(s, delim) Splits string by delimiter strtok(s, ",")
sprintf(buf, fmt, ...) Writes formatted string to buffer sprintf(buf, "%d", 42)
sscanf(s, fmt, ...) Reads formatted data from string sscanf("42", "%d", &n)

String Basics - Null Terminator and fgets

String Basics - Null Terminator and fgets
#include <stdio.h>
#include <string.h>

int main() {
    char name[] = "Alice";

    // Print string
    printf("Name: %s\n", name);
    printf("Length: %zu\n", strlen(name));  // 5

    // Access individual characters
    printf("Characters: ");
    for (int i = 0; name[i] != '\0'; i++) {
        printf("%c ", name[i]);
    }
    printf("\n");

    // Null terminator
    printf("name[5] = %d (null char)\n", name[5]);  // 0

    // Reading string with fgets (safer than scanf or gets)
    char input[100];
    printf("Enter your name: ");
    fgets(input, sizeof(input), stdin);

    // Remove trailing newline that fgets includes
    input[strcspn(input, "\n")] = '\0';
    printf("Hello, %s!\n", input);

    return 0;
}

string.h Functions - strlen, strcpy, strcat, strcmp

string.h Functions - strlen, strcpy, strcat, strcmp
#include <stdio.h>
#include <string.h>

int main() {
    char s1[50] = "Hello";
    char s2[] = "World";
    char s3[50];

    // strlen
    printf("strlen(\"%s\") = %zu\n", s1, strlen(s1));  // 5

    // strcpy
    strcpy(s3, s1);
    printf("strcpy: s3 = \"%s\"\n", s3);  // Hello

    // strcat
    strcat(s1, " ");
    strcat(s1, s2);
    printf("strcat: s1 = \"%s\"\n", s1);  // Hello World

    // strcmp
    int cmp = strcmp("apple", "banana");
    printf("strcmp(\"apple\",\"banana\") = %d\n", cmp);  // negative (a < b)
    printf("strcmp(\"abc\",\"abc\")     = %d\n", strcmp("abc","abc"));  // 0

    // strchr - find first occurrence of character
    char *pos = strchr("Hello World", 'W');
    if (pos) printf("strchr found 'W' at: \"%s\"\n", pos);  // World

    // strstr - find substring
    char *sub = strstr("Hello World", "World");
    if (sub) printf("strstr found: \"%s\"\n", sub);  // World

    return 0;
}

String Operations - Reverse and Palindrome Check

String Operations - Reverse and Palindrome Check
#include <stdio.h>
#include <string.h>

void reverseString(char str[]) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        char temp = str[i];
        str[i] = str[len - 1 - i];
        str[len - 1 - i] = temp;
    }
}

int isPalindrome(char str[]) {
    int len = strlen(str);
    for (int i = 0; i < len / 2; i++) {
        if (str[i] != str[len - 1 - i]) return 0;
    }
    return 1;
}

int main() {
    char s1[] = "Hello";
    reverseString(s1);
    printf("Reversed: %s\n", s1);  // olleH

    char words[][20] = {"racecar", "hello", "madam", "world"};
    for (int i = 0; i < 4; i++) {
        printf("\"%s\" is %s\n", words[i],
               isPalindrome(words[i]) ? "a palindrome" : "not a palindrome");
    }

    return 0;
}

/*
Reversed: olleH
"racecar" is a palindrome
"hello" is not a palindrome
"madam" is a palindrome
"world" is not a palindrome
*/

Applied guide for C

Use C when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real C task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.

A reliable practice flow is: create the smallest working function, add one normal case, add one edge case such as empty strings, spaces, and missing separators, and then confirm the result with compiler warnings and printed output. If the result surprises you, reduce the code until the behavior is visible again.

The most common trap here is assuming the text has the expected length or delimiter. Avoid it by writing one sentence before the code that explains why C is the right choice. After the code runs, verify the lesson by doing this: print both the value and its length.

  • Identify the exact problem solved by C.
  • Trace pointer, array, or file buffer before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a small command-line program so the idea feels concrete.
Key Takeaways
  • I can explain where C fits inside a small command-line program.
  • I can point to the exact pointer, array, or file buffer affected by this topic.
  • I tested a normal case and an edge case involving empty strings, spaces, and missing separators.
  • I verified the result with compiler warnings and printed output instead of assuming it worked.
  • I can describe the main mistake: assuming the text has the expected length or delimiter.
Common Mistakes to Avoid
WRONG Assuming the text has the expected length or delimiter.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test empty strings, spaces, and missing separators before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace pointer, array, or file buffer through each important step.
Tracing makes debugging faster because you can see the first incorrect state.

Practice Tasks

  • Build one small function that demonstrates C in a small command-line program.
  • Change the example to include empty strings, spaces, and missing separators and record the difference.
  • Break the example by deliberately assuming the text has the expected length or delimiter, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.

Frequently Asked Questions

Use it when the problem matches the behavior shown in the example and when the result can be verified through compiler warnings and printed output.

Start with a tiny case, then test empty strings, spaces, and missing separators. The main warning sign is assuming the text has the expected length or delimiter.

Trace pointer, array, or file buffer, predict the result, run the example, and compare your prediction with the actual output.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.