Strings in C language

Master string handling in C! Learn to manipulate text efficiently with arrays, pointers, and functions for powerful programming.

Strings in C language
Strings in C language 

Strings

String is a sequence of character that is considered as a single data item.

String is representing of character array.

Declaration 

char string name[size];

Example:- char city[9] = " NEW YORK " ;

Strings Functions

          Function         Actions 

  1. Strcat()             It combined two string 
  2. Strcmp()           It compare two string 
  3. Strcpy()            It copy one string to another string
  4. Strlen()             It counts character in a strings

strcat() function

The strcat() function joins two string together.

Strcat(string_1, string_2);

Example:

#include <stdio.h>

#include <string.h>

int main() {

    char str1[] = "Hello, ";

    char str2[] = "World!"; 

    strcat(str1, str2);     // Concatenates str2 to str1

    printf("Concatenated String: %s\n", str1);

  return 0;

}

Result : Concatenated String: Hello, World!

strcmp() function

The strcmp() function compares two strings.

Strcmp(string_1, string_2);

Example 

#include <stdio.h>

#include <string.h>

int main() {

    char str1[] = "Apple";

    char str2[] = "Banana";

    int result = strcmp(str1, str2); // Compares str1 and str2

    if (result == 0)

        printf("Strings are equal\n");

    else if (result > 0)

        printf("str1 is greater\n");

    else

        printf("str2 is greater\n");

    return 0;

}

Result:  str2 is greater

strcpy() function

The strcpy() function works almost like a string assignment oprater.

strcpy(string_1, string_2);

Example

#include <stdio.h>

#include <string.h>

int main() {

    char str1[] = "Hello";

    char str2[20];

    strcpy(str2, str1); // Copies str1 to str2

    printf("Copied String: %s\n", str2);

    return 0;

}

Result: Copied String: Hello

strlen() function

The strlen() function count and return the number of string.

n = strlen(string);

Example 

#include <stdio.h>

#include <string.h>

int main() {

    char str[] = "Programming";

    int length = strlen(str); // Finds length of str

    printf("Length of string: %d\n", length);

    return 0;

}

Result: Length of string: 11

Post a Comment