Chapter 4- Programming in C----> String Function

 String Function

1. `strlen() à Get string length

#include <stdio.h>

#include <string.h>

int main() {

    char str[] = "Hello";

    printf("Length of string: %zu\n", strlen(str));

    return 0;

}

Output:

Length of string: 5

 

2. `strcpy()à Copy one string to another

#include <stdio.h>

#include <string.h>

int main() {

    char src[] = "C Language";

    char dest[20];

    strcpy(dest, src);

    printf("Copied string: %s\n", dest);

    return 0;

}

Output:

Copied string: C Language

 

3. strcat() à Concatenate (append) strings

#include <stdio.h>

#include <string.h>

int main() {

    char str1[20] = "Hello, ";

    char str2[] = "World!";

    strcat(str1, str2);

 

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

    return 0;

}

Output:

Concatenated string: Hello, World!

 

4. strcmp() àCompare two strings

#include <stdio.h>

#include <string.h>

int main() {

    char str1[] = "Apple";

    char str2[] = "Banana";

    int result = strcmp(str1, str2);

    if (result == 0)

        printf("Strings are equal\n");

    else if (result < 0)

        printf("str1 is less than str2\n");

    else

        printf("str1 is greater than str2\n");

    return 0;

}

 

 

Output:

str1 is less than str2

 

5. strchr() àFind first occurrence of a character

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[] = "Programming";

    char *ptr = strchr(str, 'g');

 

    if (ptr != NULL)

        printf("First 'g' found at position: %ld\n", ptr - str);

    else

        printf("Character not found\n");

 

    return 0;

}Output:

First 'g' found at position: 3

Popular posts from this blog

Computer