Cover Image for C String Test
85 views

C String Test

The testing strings often involves comparing strings for equality or performing other string-related operations. Here’s a simple example of testing strings in C:

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

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[] = "Hello";
    char str4[] = "HELLO";

    // Compare two strings for equality
    if (strcmp(str1, str3) == 0) {
        printf("str1 and str3 are equal.\n");
    } else {
        printf("str1 and str3 are not equal.\n");
    }

    // Case-insensitive string comparison
    if (strcasecmp(str1, str4) == 0) {
        printf("str1 and str4 are equal (case-insensitive).\n");
    } else {
        printf("str1 and str4 are not equal (case-insensitive).\n");
    }

    // Test string length
    if (strlen(str2) < 5) {
        printf("str2 is shorter than 5 characters.\n");
    } else {
        printf("str2 is 5 characters or longer.\n");
    }

    // Concatenate strings
    strcat(str1, " ");
    strcat(str1, str2);
    printf("Concatenated string: %s\n", str1);

    return 0;
}

In this example, we perform various string-related tests:

  1. We use strcmp() to compare str1 and str3 for equality and print the result.
  2. We use strcasecmp() to perform a case-insensitive comparison between str1 and str4 and print the result.
  3. We use strlen() to check the length of str2 and print whether it’s shorter than 5 characters or not.
  4. We use strcat() to concatenate str1 and str2, adding a space in between, and then print the concatenated string.

You can adapt and extend these string tests based on your specific requirements in your C program. Testing and comparing strings are common tasks in C programming, especially when working with user input or data processing.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS