Ad Code

Responsive Advertisement

Strings in C ? With Example

 Strings in C

The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character array or the string is used to manipulate text such as word or sentences. Each character in the array occupies one byte of memory, and the last character must always be 0. The termination character ('\0') is important in a string since it is the only way to identify where the string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

Let's see the example of declaring string by char array in C language.

Declaration and Initialization:

c
#include <stdio.h> int main() { // Declaration and Initialization char str1[] = "Hello, World!"; // Automatically includes null character char str2[12] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '\0'}; printf("str1: %s\n", str1); printf("str2: %s\n", str2); return 0; }

String Input:

c
#include <stdio.h> int main() { char str[50]; // Input a string printf("Enter a string: "); scanf("%s", str); // Note: %s stops reading input at the first whitespace printf("You entered: %s\n", str); return 0; }

String Manipulation Functions:

C provides several standard library functions for working with strings, which are declared in the <string.h> header file. Some commonly used functions include:

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

Example:

c
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "World"; // Concatenate str2 to str1 strcat(str1, str2); printf("Concatenated string: %s\n", str1); return 0; }

String Comparison:

c
#include <stdio.h> #include <string.h> int main() { char str1[] = "apple"; char str2[] = "banana"; // Compare strings int result = strcmp(str1, str2); if (result == 0) { printf("The 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; }


Remember to always ensure that your strings are properly null-terminated to avoid unexpected behavior when using string functions.

Difference between char array and string literal

There are two main differences between char array and literal.

1. We need to add the null character '\0' at the end of the array by ourself whereas, it is appended internally by the compiler in the case of the character array.

2. The string literal cannot be reassigned to another set of characters whereas, we can reassign the characters of the array.

String Example in C

Let's see a simple example where a string is declared and being printed. The '%s' is used as a format specifier for the string in c language.

c
#include <stdio.h> #include <string.h> int main() { // Declare and initialize a string char greeting[] = "Hello, "; // Concatenate another string char name[] = "John"; strcat(greeting, name); // Print the concatenated string printf("Greeting: %s\n", greeting); // Find the length of the string int length = strlen(greeting); printf("Length of the greeting: %d\n", length); // Compare strings char anotherName[] = "Alice"; int comparisonResult = strcmp(name, anotherName); if (comparisonResult == 0) { printf("The names are the same.\n"); } else { printf("The names are different.\n"); } return 0; }


Explanation:

1. Concatenation: The program uses the strcat function to concatenate the name string to the end of the greeting string.

2. Length: It then uses the strlen function to find the length of the concatenated string.

3. Comparison: Finally, it compares the name and anotherName strings using the strcmp function and prints whether the names are the same or different.

 Output :

yaml
Greeting: Hello, John Length of the greeting: 13 The names are different.
Please note that this is a basic example, and in a real-world scenario, you should always be mindful of buffer sizes and ensure that your strings are properly null-terminated to avoid unexpected behavior.

Traversing String


Traversing a string means accessing each character in the string one by one. You can use loops, such as for or while, to iterate through the characters of a string until the null character '\0' is encountered.

Here's an example of traversing a string in C using a for loop:

c
#include <stdio.h> int main() { // Declare and initialize a string char myString[] = "Hello"; // Traverse the string using a for loop for (int i = 0; myString[i] != '\0'; ++i) { printf("Character at position %d: %c\n", i, myString[i]); } return 0; }

In this example:

The loop iterates through each character of the myString array.

The loop condition myString[i] != '\0' ensures that the loop continues until the null character '\0' is encountered, indicating the end of the string.

Inside the loop, myString[i] is used to access each character in the string, and its position (i) is printed along with the character.

Output:

arduino
Character at position 0: H Character at position 1: e Character at position 2: l Character at position 3: l Character at position 4: o


This output shows each character in the string along with its position in the array. You can use a similar approach with a while loop or other constructs based on your requirements.

Using the length of string

You can use the length of a string to iterate through its characters by determining the length of the string using the strlen function. Here's an example using a for loop and the length of the string:

c
#include <stdio.h> #include <string.h> int main() { // Declare and initialize a string char myString[] = "Hello"; // Get the length of the string int length = strlen(myString); // Traverse the string using a for loop with the length for (int i = 0; i < length; ++i) { printf("Character at position %d: %c\n", i, myString[i]); } return 0; }


In this example:

The strlen function is used to find the length of the myString array.

The loop iterates from 0 to length - 1 to access each character of the string.

Inside the loop, myString[i] is used to access each character, and its position (i) is printed along with the character.

Output :

arduino
Character at position 0: H Character at position 1: e Character at position 2: l Character at position 3: l Character at position 4: o


This approach ensures that you don't go beyond the actual length of the string and avoids accessing memory beyond the null character at the end of the string.

Using the null character

The null character ('\0') is used to signify the end of a string in C. When traversing a string, you can use the null character as a termination condition in loops. Here's an example using a while loop and the null character:

c
#include <stdio.h> int main() { // Declare and initialize a string char myString[] = "Hello"; // Traverse the string using a while loop and the null character int i = 0; while (myString[i] != '\0') { printf("Character at position %d: %c\n", i, myString[i]); ++i; } return 0; }


In this example:

The loop condition myString[i] != '\0' ensures that the loop continues until the null character '\0' is encountered.

Inside the loop, myString[i] is used to access each character in the string, and its position (i) is printed along with the character.

The loop increments the index i to move to the next character in the string.

Output:

arduino
Character at position 0: H Character at position 1: e Character at position 2: l Character at position 3: l Character at position 4: o


Using the null character as the termination condition ensures that you only process characters within the valid range of the string.

Accepting string as the input


To accept a string as input in C, you can use the scanf function with the %s format specifier. However, note that %s in scanf stops reading input at the first whitespace character. If you need to read a whole line including spaces, it's often better to use fgets instead.

Here's an example using both scanf and fgets:

Using scanf:

c
#include <stdio.h> int main() { char myString[50]; // Accept a string as input using scanf printf("Enter a string: "); scanf("%s", myString); // Print the entered string printf("You entered: %s\n", myString); return 0; }

In this example, scanf reads the string until it encounters the first whitespace character (space, tab, newline, etc.). If you enter a string with spaces, it will only take the characters before the first space.

Using fgets:

c
#include <stdio.h> int main() { char myString[50]; // Accept a string as input using fgets printf("Enter a string: "); fgets(myString, sizeof(myString), stdin); // Print the entered string printf("You entered: %s", myString); return 0; }


With fgets, you can input an entire line, including spaces, until you press Enter. It reads at most sizeof(myString) - 1 characters (to leave space for the null character \0) or until a newline character is encountered.

Choose the method that suits your input requirements. If you need to read a single word without spaces, scanf can be used. If you need to read a whole line, fgets is a safer choice.

Some important points


Null-terminated Strings:

1. In C, strings are represented as arrays of characters terminated by a null character '\0'.

2. The null character marks the end of the string and is essential for string-related functions to work correctly.


String Initialization:

1. Strings can be initialized using array syntax or by assigning string literals.

2. Example: char str[] = "Hello";


String Input:

1. Use scanf with the %s format specifier for reading strings until the first whitespace.

2. fgets is preferable for reading entire lines, including spaces.



String Functions:

1. Standard library functions for string manipulation are declared in <string.h>.

2. Common functions include strlen, strcpy, strcat, strcmp, etc.


String Modification:

1. Be cautious when modifying strings to avoid buffer overflows.

2. Use functions like strcpy, strcat, or manipulate individual characters carefully.


Pointers with strings

We have used pointers with the array, functions, and primitive data types so far. However, pointers can be used to point to the strings. There are various advantages of using pointers to point strings. Let us consider the following example to access the string via the pointer.

String as an Array:

Strings in C are typically represented as arrays of characters.
Example: char myString[] = "Hello";


String as a Pointer:

Strings can be represented using character pointers.
Example: char *str = "Hello";


Accessing Characters with Pointers:

You can use pointers to traverse through the characters of a string.
Example:

c
char *str = "Hello"; while (*str != '\0') { printf("%c", *str); str++; }


Pointer Arithmetic:

Pointers can be incremented or decremented to navigate through the characters of a string.
Example:

c
char *str = "Hello"; while (*str != '\0') { printf("%c", *str); str++; }


Passing Strings to Functions:

Strings can be passed to functions using pointers.
Example:

c
void printString(char *str) { while (*str != '\0') { printf("%c", *str); str++; } }


Modifying Strings with Pointers:

Be cautious when modifying strings using pointers to avoid undefined behavior.
Example:

c
char myString[] = "Hello"; char *ptr = myString; while (*ptr != '\0') { *ptr = 'X'; // Modifying characters ptr++; }


Dynamic Memory Allocation for Strings:

Pointers are commonly used for dynamically allocating memory for strings.
Example:

c
char *dynamicString = malloc(10 * sizeof(char)); strcpy(dynamicString, "Dynamic");

Common String Functions with Pointers:

String manipulation functions often accept pointers as arguments.
Example:

c
char str1[] = "Hello"; char str2[] = "World"; char *result = strcat(str1, str2); // Concatenating two strings

Remember to handle pointers and strings carefully to avoid buffer overflows and undefined behavior. Understanding the relationship between pointers and arrays is crucial for efficient string manipulation in C.

Post a Comment

0 Comments