Strings and Manipulate Them in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to create and manipulate strings in C programming. You will explore different methods to define strings, format them using printf, determine their length with strlen, and compare them with strncmp. These fundamental string operations are essential for building robust and flexible C applications.

The lab covers the following steps: defining strings using pointer notation, defining strings using local array notation, formatting strings with printf, determining string length with strlen, and comparing strings with strncmp. By the end of this lab, you will have a solid understanding of working with strings in C and be able to apply these techniques in your own projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/CompoundTypesGroup(["Compound Types"]) c(("C")) -.-> c/PointersandMemoryGroup(["Pointers and Memory"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/operators("Operators") c/CompoundTypesGroup -.-> c/arrays("Arrays") c/CompoundTypesGroup -.-> c/strings("Strings") c/PointersandMemoryGroup -.-> c/pointers("Pointers") c/PointersandMemoryGroup -.-> c/memory_address("Memory Address") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/operators -.-> lab-438258{{"Strings and Manipulate Them in C"}} c/arrays -.-> lab-438258{{"Strings and Manipulate Them in C"}} c/strings -.-> lab-438258{{"Strings and Manipulate Them in C"}} c/pointers -.-> lab-438258{{"Strings and Manipulate Them in C"}} c/memory_address -.-> lab-438258{{"Strings and Manipulate Them in C"}} c/output -.-> lab-438258{{"Strings and Manipulate Them in C"}} end

Define Strings Using Pointer Notation

In this step, you'll learn how to define strings using pointer notation in C. Pointer notation provides a flexible way to create and manipulate strings in C programming.

First, let's create a new file to demonstrate string definition with pointer notation:

cd ~/project
touch string_pointer.c

Now, enter the following code:

#include <stdio.h>

int main() {
    // Define a string using pointer notation
    char *greeting = "Hello, C Programming!";

    // Print the string
    printf("Greeting: %s\n", greeting);

    return 0;
}

Compile and run the program:

gcc string_pointer.c -o string_pointer
./string_pointer

Example output:

Greeting: Hello, C Programming!

Let's break down the code:

  • char *greeting declares a pointer to a character (string)
  • "Hello, C Programming!" is a string literal stored in memory
  • The pointer greeting points to the first character of the string
  • printf() uses %s format specifier to print the entire string

You can also modify the pointer to point to different parts of the string:

#include <stdio.h>

int main() {
    char *greeting = "Hello, C Programming!";

    // Point to a specific part of the string
    char *partial = greeting + 7;

    printf("Original string: %s\n", greeting);
    printf("Partial string: %s\n", partial);

    return 0;
}

Example output:

Original string: Hello, C Programming!
Partial string: C Programming!

Define Strings Using Local Array Notation

In this step, you'll learn how to define strings using local array notation in C. This method provides another way to create and initialize strings with more direct control over the character array.

Let's create a new file to demonstrate string definition using local array notation:

cd ~/project
touch string_array.c

Enter the following code:

#include <stdio.h>

int main() {
    // Define a string using local array notation
    char greeting[30] = "Hello, C Programming!";

    // Print the string
    printf("Greeting: %s\n", greeting);

    return 0;
}

Compile and run the program:

gcc string_array.c -o string_array
./string_array

Example output:

Greeting: Hello, C Programming!

Let's explore some variations of local array notation:

#include <stdio.h>

int main() {
    // Define an array with explicit initialization
    char name[10] = {'J', 'o', 'h', 'n', '\0'};

    // Define an array with partial initialization
    char city[20] = "New York";

    // Define an array without specifying size
    char message[] = "Welcome to C Programming!";

    printf("Name: %s\n", name);
    printf("City: %s\n", city);
    printf("Message: %s\n", message);

    return 0;
}

Example output:

Name: John
City: New York
Message: Welcome to C Programming!

Key points about local array notation:

  • You can specify the array size explicitly
  • The '\0' (null terminator) is crucial to mark the end of the string
  • Arrays can be initialized with individual characters or as string literals
  • When not fully initialized, remaining elements are set to zero

Format Strings with printf

In this step, you'll learn how to use printf() to format strings and various data types in C. The printf() function provides powerful string formatting capabilities.

Let's create a new file to demonstrate string formatting:

cd ~/project
touch string_formatting.c

Enter the following code to explore different formatting options:

#include <stdio.h>

int main() {
    // Basic string formatting
    char name[] = "Alice";
    int age = 30;
    float height = 5.8;

    // Simple string output
    printf("Name: %s\n", name);

    // Formatting with multiple variables
    printf("Profile: %s is %d years old\n", name, age);

    // Formatting with floating-point precision
    printf("Height: %.1f meters\n", height);

    // Width and alignment
    printf("Name (right-aligned): %10s\n", name);
    printf("Name (left-aligned):  %-10s\n", name);

    // Mixing different format specifiers
    printf("Details: %s, %d years, %.1f meters\n", name, age, height);

    return 0;
}

Compile and run the program:

gcc string_formatting.c -o string_formatting
./string_formatting

Example output:

Name: Alice
Profile: Alice is 30 years old
Height: 5.8 meters
Name (right-aligned):      Alice
Name (left-aligned): Alice
Details: Alice, 30 years, 5.8 meters

Common format specifiers:

  • %s: Strings
  • %d: Integers
  • %f: Floating-point numbers
  • %.1f: Floating-point with 1 decimal place
  • %10s: Right-aligned with 10 character width
  • %-10s: Left-aligned with 10 character width

Let's explore more advanced formatting:

#include <stdio.h>

int main() {
    // Hexadecimal and octal representations
    int number = 255;
    printf("Decimal: %d\n", number);
    printf("Hexadecimal: %x\n", number);
    printf("Octal: %o\n", number);

    // Padding with zeros
    printf("Padded number: %05d\n", 42);

    return 0;
}

Example output:

Decimal: 255
Hexadecimal: ff
Octal: 377
Padded number: 00042

Determine String Length with strlen

In this step, you'll learn how to use the strlen() function to determine the length of strings in C. The strlen() function is part of the <string.h> library and provides an easy way to count characters in a string.

Let's create a new file to demonstrate string length calculation:

cd ~/project
touch string_length.c

Enter the following code to explore strlen():

#include <stdio.h>
#include <string.h>

int main() {
    // Define strings of different lengths
    char greeting[] = "Hello, World!";
    char name[] = "Alice";
    char empty[] = "";

    // Calculate and print string lengths
    printf("Greeting: %s\n", greeting);
    printf("Greeting length: %lu characters\n", strlen(greeting));

    printf("Name: %s\n", name);
    printf("Name length: %lu characters\n", strlen(name));

    printf("Empty string length: %lu characters\n", strlen(empty));

    return 0;
}

Compile and run the program:

gcc string_length.c -o string_length
./string_length

Example output:

Greeting: Hello, World!
Greeting length: 13 characters
Name: Alice
Name length: 5 characters
Empty string length: 0 characters

Let's explore a more practical example of using strlen():

#include <stdio.h>
#include <string.h>

int main() {
    char input[100];

    printf("Enter a string: ");
    fgets(input, sizeof(input), stdin);

    // Remove newline character if present
    input[strcspn(input, "\n")] = 0;

    // Calculate and print string length
    size_t length = strlen(input);

    printf("You entered: %s\n", input);
    printf("String length: %lu characters\n", length);

    // Demonstrate length-based operations
    if (length > 10) {
        printf("This is a long string!\n");
    } else if (length > 0) {
        printf("This is a short string.\n");
    } else {
        printf("You entered an empty string.\n");
    }

    return 0;
}

Key points about strlen():

  • Returns the number of characters before the null terminator
  • Does not count the null terminator
  • Works with character arrays and string literals
  • Part of <string.h> library, so include this header
  • Returns size_t type (unsigned long)

Compare Strings with strncmp

In this step, you'll learn how to use the strncmp() function to compare strings in C. The strncmp() function allows you to compare a specified number of characters between two strings.

Let's create a new file to demonstrate string comparison:

cd ~/project
touch string_compare.c

Enter the following code to explore strncmp():

#include <stdio.h>
#include <string.h>

int main() {
    // Define strings for comparison
    char str1[] = "Hello, World!";
    char str2[] = "Hello, Everyone!";
    char str3[] = "Hello, World!";

    // Compare entire strings
    printf("Full string comparison:\n");
    int result1 = strncmp(str1, str2, strlen(str1));
    int result2 = strncmp(str1, str3, strlen(str1));

    printf("str1 vs str2: %d\n", result1);
    printf("str1 vs str3: %d\n", result2);

    // Compare first few characters
    printf("\nPartial string comparison:\n");
    int result3 = strncmp(str1, str2, 7);
    printf("First 7 characters of str1 vs str2: %d\n", result3);

    return 0;
}

Compile and run the program:

gcc string_compare.c -o string_compare
./string_compare

Example output:

Full string comparison:
str1 vs str2: -1
str1 vs str3: 0

Partial string comparison:
First 7 characters of str1 vs str2: 0

Let's create a more practical example of string comparison:

#include <stdio.h>
#include <string.h>

int main() {
    // Password verification example
    char stored_password[] = "SecretPass123";
    char input_password[20];

    printf("Enter password: ");
    scanf("%19s", input_password);

    // Compare first 10 characters of the password
    int comparison = strncmp(stored_password, input_password, 10);

    if (comparison == 0) {
        printf("Access granted!\n");
    } else {
        printf("Access denied!\n");
    }

    return 0;
}

Key points about strncmp():

  • Compares up to a specified number of characters
  • Returns 0 if strings match for the specified length
  • Returns negative value if first string is lexicographically less
  • Returns positive value if first string is lexicographically greater
  • Part of <string.h> library
  • Useful for partial string comparisons

Understanding strncmp() return values:

  • 0: Strings are equal for the specified length
  • < 0: First string comes before second string
  • 0: First string comes after second string

Summary

In this lab, you learned how to define strings using both pointer notation and local array notation in C programming. With pointer notation, you can create and manipulate strings flexibly by using a character pointer. With local array notation, you have more direct control over the character array. You also learned how to format strings with printf(), determine string length with strlen(), and compare strings with strncmp(). These string manipulation techniques are fundamental skills for working with text data in C.