Strings in C

C programming language provides various features and techniques to the users and Strings is one of them. A string is generally a text that is enclosed in double quotes. C has a standard library called <string.h> which contains many functions and the main purpose of these functions is to perform complex operations on Strings.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is String in C?

Strings are an array of characters. It is a one dimensional array. The only difference between a character array and a string is that the string is terminated with a null character ‘\0’.

The termination character(‘\0’) is the only important thing by which you can identify if it is string or not. You can represent the string using double quotes(“”). And, using single quotes(‘’), you can represent a single character.

Declaration of Strings in C

String declaration is as simple as the declaration of a one-dimensional array. There are two ways to declare a string in C:-

  • By char array
  • By string literal

Example of declaring string by char array in C:-

char tutorial[10]={'T', 'e', 'c', 'h', 'V', 'i', 'd', 'v', 'a', 'n', '\0'};

Note:- While declaring, size is not mandatory.

We can also declare the above string like below!

char tutorial[]={'T', 'e', 'c', 'h', 'V', 'i', 'd', 'v', 'a', 'n', '\0'};

Example of declaring string by string literal in C:-

char tutorial[]="TechVidvan";

In the above case, the compiler will add a null character(‘\0’) at the end of the string.

Syntax:-

char name_str[size];

In the above expression, function name is name_str and size is the length of the characters.

Initialization of a string in C

Strings can be initialized in different ways. Below are some examples of string initialization.

Example:- Initializing a string in C

char str[] = "Tech";
char str[50] = "TechVidvan";
char str[] = {'T','e','c','h','V','i','d','v','a','n','\0'};

Memory representation of string “Tech”:-

Tech\0

  0         1                 2           3       4

Basic Example of initializing and declaring a string:-

#include <stdio.h>

int main() {
  char s[]="TechVidvan!";
  printf("%s",s);
  return 0;
}

Output

TechVidvan!

You can use the %s access specifier to directly read or print strings.

Assigning values to String in C

In strings, you can assign values to the string like below:-

char s[30] = "TechVidvan";

Read a string in C:

We can use functions like scanf(), fgets(), gets() to read a string from the user.

Example:- Reading a string in C

#include <stdio.h>

int main() {
  char s[10];
  printf("Enter your name: \n");
  scanf("%s",s);
  printf("Your name is: %s",s);
  return 0;
}

In the above code, we use scanf() function to read string from the user and we use %s format specifier without using “&” because an array acts as a pointer.

The main problem with scanf() function is that it never reads the entire string in C. It will break the process as soon as whitespace, form feed, vertical tab or newline occurs.

For example, suppose you want to read “TechVidvan Tutorials” and if you use scanf() then it will never read the entire string because whitespace is there between the two names. That’s why the scanf() function will only read “TechVidvan”.

gets() function in C

But you can bypass this with the help of gets() function. With the help of this function, you can read the entire string. It ignores whitespaces and stops reading when a newline is entered.

Example:- gets() function in C

#include <stdio.h>

int main() {
  char s[10];
  printf("Enter your name: \n");
  gets(s);
  printf("Your name is: %s",s);
  return 0;
}

Output

Enter your name:
Your name is: Raj Prasad

But there is a dangerous problem in the get() function also. The gets() function continues reading until it finds a newline or encounters EOF and may overflow the bounds of the buffer it was given.

Alternative to this, you can use the fgets() function to bypass the above situation.

Example:- fgets() function in C

#include <stdio.h>

int main() {
  char s[15];
  printf("Enter your name: \n");
  fgets(s,15,stdin);
  printf("Your name is: %s",s);
  return 0;
}

Output

Enter your name:
Your name is: Raj Prasad

The arguments that fgets() function accept are:-
The string name.
Number of characters to read.
stdin:- Purpose of this is to read from standard input which is from the keyboard.

Print a string in C

You already know that printf() function is used for printing strings in C. And with printf(), you have to use %s format specifier to print the string.

Example:- Printing a string in C

printf("%s", str_name);

Apart from this function, you can also use fputs(), puts() function to print the string.

fputs() function in C:-

This function helps you in printing the string to the display.

Example:- fputs() function in C

#include <stdio.h>

int main() {
  char tutorial[25];
  printf("Enter your favourite website to learn C: \n");
  fgets(tutorial,25,stdin);
  fputs(tutorial,stdout);
  return 0;
}

Output

Enter your favourite website to learn C:
It’s TechVidvan!

The arguments that fgets() function accept are:-

  • Name of the string.
  • stdout:- The purpose of this is to print the output to the screen.

puts() function in C

The puts() function helps you in printing the string to the display.

Example:- puts() function in C

#include <stdio.h>
int main() {
  char str_name[25];
  printf("Enter your favourite Food: \n");
  fgets(str_name,25,stdin);
  puts(str_name);
  return 0;
}

Output

Enter your favourite Food:
Biryani!

Passing strings to function in C

You can pass strings to the function in a similar way as you pass arrays to a function.

Example:- Passing strings to function

#include <stdio.h>
void display_string(char best_tutorial[]){
  printf("Best Website to learn C programming is: %s",best_tutorial);
}
int main() {
  char best_tutorial[] = "TechVidvan!";
  display_string(best_tutorial);
  return 0;
}

Output

Best Website to learn C programming is: TechVidvan!

You can use pointers to point to the string which you want to print. There are several benefits of using pointers to point to the string.

Strings and Pointers in C

Strings and pointers are one of the most important and useful topics in the C programming language. You can use a pointer with a string like you use a pointer with an array.

Example:- Strings and Pointers in C

#include <stdio.h>
int main() {
  char str_name[] = "TechVidvan Tutorials: Strings and Pointers!";
  char *point = str_name;
  printf("%s",point);
  return 0;
}

Output

TechVidvan Tutorials: Strings and Pointers!

In the above example, point is declared as a pointer to the array of characters str_name. You cannot just copy the string into another string. For that, you will have to use a pointer to store the string. In the above example, we used a pointer to copy the string into another.

Traversing String in C

Strings traversing is one of the most important concepts in any programming language. Suppose, you want to manipulate a large text then string traversing will help you to manipulate the text.

There are two ways to traverse a string in C:-

  • Using the length of the string.
  • Using the null character.

Let us see an example of each:

Example of using the length of the string:-

#include<stdio.h>  
void main ()  
{  
char str_name[20] = "TechVidvan";  
int each = 0;   
int incr = 0;  
while(each<11)  
{  
if(str_name[each]=='a' || str_name[each] == 'e' || str_name[each] == 'i' || str_name[each] == 'u' || str_name[each] == 'o')  
{  
incr++;  
}  
each++;  
}  
printf("Number of vowels in '%s' is: %d",str_name,incr);  
}

Output

Number of vowels in ‘TechVidvan’ is: 3

Example of Using the null character in C

#include<stdio.h>  
void main ()  
{  
char str_name[20] = "TechVidvan";  
int each = 0;   
int incr = 0;  
while(str_name[each] != NULL)  
{  
if(str_name[each]=='a' || str_name[each] == 'e' || str_name[each] == 'i' || str_name[each] == 'u' || str_name[each] == 'o')  
{  
incr++;  
}  
each++;  
}  
printf("Number of vowels in '%s' is: %d",str_name,incr);  
}

Output

Number of vowels in ‘TechVidvan’ is: 3

String functions in C

You often need to manipulate large texts according to the required problem. Doing this manually will make your programming complex and large.

To get rid of this, C supports various string handling functions in the standard library “string.h”.

Below are the string handling functions that C supports:-

  • strcpy(s1, s2):- Copies string s2 into string s1.
  • strcat(s1, s2):- Concatenates string s2 onto the end of string s1.
  • strlen(s1):- Returns the length of string s1.
  • strcmp(s1, s2):- Compares string s1 and s2.
  • strlwr(s1):- Converts string s1 to lowercase.
  • strupr(s1):- Converts string s1 to uppercase.
  • strchr(s1, ch):- Returns a pointer to the first occurrence of character ch in string s1.
  • strstr(s1, s2):- Returns a pointer to the first occurrence of string s2 in string s1.
  • strrev(s1):- Reverse the string s1.
  • strncmp(s1, s2, n):- It returns greater than 0 if s1>s2. And it returns less than 0 if s1<s2. It returns 0 if the first n characters of s1 is equal to the first n characters of s2.
  • strncpy(s1, s2, n):- Copies the first n characters of s2 to s1.
  • strncat(s1, s2, n):- Concatenates first n characters of s2 to the end of s1.

Example:- String Handling Functions in C

#include <stdio.h>
#include <string.h>
int main () {
char s1[20] = "Greeting from ";
char s2[20] = "TechVidvan!";
char s3[20];
int len;
int cmp;
strcpy(s3, s1); // copies string s1 into s3!
printf("Coping string s1 into s3: %s\n", s3 );
strcat( s1, s2); // concatenates s1 and s2!
printf("Concatenating string s1 and s2: %s\n", s1 );
len = strlen(s1); // length of string s1
printf("Length of string s1 is: %d\n", len );
// comparing string s1 and s2!
cmp = strcmp(s1,s2);
if (cmp == 0){
  printf("String s1 and s2 are equal!\n");
}
else{
  printf("String s1 and s2 are not equal!\n");
}
return 0;
}

Output

Coping string s1 into s3: Greeting from
Concatenating string s1 and s2: Greeting from TechVidvan!
Length of string s1 is: 25
String s1 and s2 are not equal!

Note:– You have to include “#include <string.h>” to run string handling functions.

Converting string to number in C

In C, stdio.h library contains the functions which help in converting a string to a number. Following are the functions:-

  • int atoi(string):- Mainly used to convert a string to the equivalent int value. It stands for ASCII to integer.
  • double atof(string):- Mainly used to convert a string to the equivalent double value. It stands for ASCII to float.
  • long int aol(string):- Mainly used to convert a string to the equivalent long integer value.

Example:- Converting string to a number

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
  char str_id[10]="TechVidvan";
  int num;
  num = atoi(str_id);
  printf("Integer Value: %d\n",num);
  char str_id_1[10]="5555555";
  int num1;
  num1 = atoi(str_id_1);
  printf("Integer Value: %d\n",num1);
  return 0;
}

Output

Integer Value: 0
Integer Value: 5555555

Note:- If you declare a string like char *string = “Hi”. Then this is a constant and you can’t modify it.

Summary

You must declare or initialize a string before using it. A string is an array of characters. You cannot say that ‘A’ is a string. It is a character. C supports various string handling functions which helps you in manipulating large texts. To use these functions, you have to include the string.h library. In C, we can convert strings to numbers which is useful for coding and decoding processes.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.