C Strings

In C programming language, a string is an array of characters that is terminated by a null character ('\0'). Strings in C are represented by the char data type, and are used to store and manipulate text.

To declare a string in C, you need to use the char data type and an array of characters. The basic syntax for declaring a string is as follows:


 
char string_name[size];

 

Here, string_name is the name of the string and size is the size of the array. For example, to declare a string named message that can hold up to 50 characters, you would use the following code:

char message[50];

 

To initialize a string in C, you can use a string literal enclosed in double quotes. For example, to initialize the message string with the value "Hello, world!", you would use the following code:

char message[] = "Hello, world!";

 

You can also initialize a string using an array of characters. For example, to initialize the message string with the value "Hello", you would use the following code:

char message[] = {'H', 'e', 'l', 'l', 'o', '\0'};

You can access individual characters in a string using their index. For example, to print the first character of the message string, you would use the following code:

printf("%c\n", message[0]);

 

This prints the first character of the message string, which is 'H'.

You can also use various string manipulation functions in C to perform operations on strings. Some commonly used string functions in C are:

  • strlen: Returns the length of a string.
  • strcpy: Copies one string to another.
  • strcat: Concatenates two strings.
  • strcmp: Compares two strings.

Here's an example program that uses some of these functions:

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

int main() {
    char message[] = "Hello, world!";
    int length = strlen(message);
    char copy[50];
    strcpy(copy, message);
    strcat(copy, " Goodbye!");
    int result = strcmp(message, copy);
    printf("Length: %d\n", length);
    printf("Copy: %s\n", copy);
    printf("Result: %d\n", result);
    return 0;
}

 

This program first declares a string named message and initializes it with the value "Hello, world!". It then uses the strlen function to determine the length of the string, and stores the result in an integer variable named length.

Next, the program declares a new string named copy, and uses the strcpy function to copy the contents of the message string to the copy string. It then uses the strcat function to append the string " Goodbye!" to the copy string.

Finally, the program uses the strcmp function to compare the message and copy strings, and stores the result in an integer variable named result. The program then prints the length of the message string, the contents of the copy string, and the result of the comparison.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

50872