Strings in C

Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’( NULL character ). String is a one dimensional array of character. We can initialize the string as char name[]={‘r’,’a’,’j’,’u’,’\0’}; Here each character occupies 1 byte of memory and last character is always NULL character.

For example:
char s[ ] = “c string”;
When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.

cstring\0

How to declare a string?

Here’s how you can declare strings:
char s[5];

s0s1s2s3s4

How to initialize strings?
You can initialize strings in a number of ways.

char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '\0'};
char c[5] = {'a', 'b', 'c', 'd', '\0'};
abcd\0
c[0] c[1] c[2] c[3] c[4]

Let’s take another example:
char c[5] = “abcde”;
Here, we are trying to assign 6 characters (the last character is ‘\0’) to a char array having 5 characters.This is bad and you should never do this.

Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Output

Enter name: Dennis Ritchie
Your name is Dennis.

Even though Dennis Ritchie was entered in the above program, only “Ritchie” was stored in the name string. It’s because there was a space after Dennis.
The scanf( ) function reads the sequence of characters until it encounters whitespace (space, newline, tab etc.).

How to read a line of text?
You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

Example 2: fgets() and puts()

#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}

Output

Enter name: Dennis Ritchie
Name: Dennis Ritchie

Here, we have used fgets() function to read a string from the user.

fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 20. Hence, we can take a maximum of 20 characters as input which is the size of the name string. To print the string, we have used puts(name);.
Note: The gets() function can also be to take input from the user. However, it is removed from the C standard. It’s because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.

Example 3: Passing string to a Function

#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}

Strings and Pointers
Similar like arrays, string .Hence, you can use pointers to manipulate elements of the string.
** We will discuss it after completing Pointers . So if you can skip it now.

Example 4: Strings and Pointers

#include <stdio.h>
int main( )
{
char name[] = "Harry Potter";
printf("%c", *name); // Output: H
printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o
char *namePtr;
namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}

String Manipulations In C Programming Using Library Functions
You need to often manipulate strings according to the need of a problem. Most, if not all, of the time string manipulation can be done manually but, this makes programming complex and large. To solve this, C supports a large number of string handling functions in the standard library “string.h”.
Few commonly used string handling functions are discussed below:

FunctionWork of Function
strlen( )computes string’s length
strcpy( )copies a string to another
strrev( )reversing a string
strcat( )concatenates(joins) two strings
strcmp( )compares two strings
strlwr( )converts string to lowercase
strupr( )converts string to uppercase

Strings handling functions are defined under “string.h” header file.
Functions gets() and puts() are two string functions to take string input from the user and display it respectively.

#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Note: Though, gets() and puts() function handle strings, both these functions are defined in “stdio.h” header file.

Calculate Length of String without Using strlen() Function

#include <stdio.h>

int main()
{
char s[] = "Programming is easy";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the string: %d", i);
return 0;
}

Output

Length of the string: 19

Here, using a for loop, we have iterated over characters of the string from i = 0 to until ‘\0’ (null character) is encountered. In each iteration, the value of i is increased by 1. When the loop ends, the length of the string will be stored in the i variable.

Copy String Without Using strcpy()

#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);
for (i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}

Output

Enter string s1: Sudipta Hazra.
String s2: Sudipta Hazra.

The above program copies the content of string s1 to string s2 manually.

Concatenate Two Strings Without Using strcat()

#include <stdio.h>
int main()
{
char s1[20] = "Urmi", s2[20] = "Sarkar",s[50];
int i, j;
for (i = 0; s1[i] != '\0'; i++)
{
s[i]= s1[i];
}
s[i++] = ' ' ;
for (j = 0; s2[j] != '\0'; ++j, ++i)
{
s[i] = s2[j];
}
// terminating s string
s[i] = '\0';
printf("After concatenation: ");
puts(s);
return 0;
}

Output

After concatenation: Urmi Sarkar

Reverse a string without using strrev( )

#include &lt;stdio.h&gt;
#include&lt;string.h&gt;
void main()
{
   char str[50], st;
   int k = 0, l;
 
   printf(&quot;\nEnter the string :&quot;);
   gets(str);
 
   l = strlen(str) -1;
 
   while (k &lt; l)
{
       st = str[k];
       str[k] = str[l];
       str[l] = stp;
       k++;
       l--;
   }
 
   printf(&quot;\nReverse string is : %s&quot;, str);
   getch();
}

Output

Enter the string : makaut
Reverse string is : tuakam

Compare two strings without using strcmp( )

#include <stdio.h>
#include <string.h>
 
int main()
{
   char str1[20], str2[20];
   int k = 0;
 
   printf("\nEnter 1st string :");
   gets(str1);
  printf("\nEnter 2nd string :");
   gets(str2);
  while(str1[k] == str2[k] && str1[k] !='\0' ||              str2[k] !='\0')
     {
k++;
}
if(str1[k] =='\0' && str2[k] =='\0')
printf("\nStrings are equal");
else
    printf("\nStrings are unequal");
   return (0);
}

Output

Enter 1st string : madam
Enter 2nd string : madan
Strings are unequal

Check weather a string is palindrome or not.

#include <stdio.h>
#include <string.h>
int main()
{
   char str1[20], str2[20];
   int k = 0;
 
   printf("\nEnter the string :");
   gets(str1);
 
  strcpy(str2, str1);  // Copying input string
 
strrev(str2);  // Reversing the string
  
if (strcmp(str1, str2) == 0)  // Comparing input string with the reverse string
   printf("\nThe string is a palindrome.");
else
    printf("\nThe string isn&#39;t a palindrome.");
   return (0);
}

Output

Enter the string : madam
The string is a palindrome.

Leave a Comment