Strings in C Programming Language.

Hello there! Hope your coding brains are in use and ready for today’s post! In today’s article of geekstocode we are going through a very important conceptual topic, i.e. Strings in C Programming Language. 

Now, you may think that you know what it is and why there is a difference but, studying in detail would provide you in depth knowledge about this topic. Hence, we have come up with all the necessary details that you require to learn in this topic.

Also, this topic can be put to you as a question in your college or entrance exams. Even as an interview question. Additionally, strings is basic beginner level concept that every programming language requires. So, it is very essential to learn and understand. 

Hence, without further ado, let’s get to the article!

What are Strings?

Before getting into Strings, we should know what it actually means.

We define strings as one dimensional array of characters which get terminated by a null character ‘\0’. Therefore, we can say that a null-terminated string contains the characters that comprise the string followed by a null.

In other words, in the C Programming language, a string is a sequence of characters that are terminated by a null character. Additionally, they are array of characters.

Now, there is a major difference between a character array and a string. Null character does not terminate a character array. Whereas, a null character or a special character ‘\0’ terminates a string.

For instance, if we create a string “Cups”, it will be an array {C,u,p,s,\0}

Thus, to hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word “Cups”.

Next, let us move on to the declaration and initialization of strings. Little different from other data types, strings have a unique way of initialization and declaration. 

Declaration of strings: 

Though declaring a string is different from other data types, it is very simple and easy to remember. Thus, let us look into its syntax.

We have written the basic syntax for declaring a string below:

char string_name[size_of_string];

In the above syntax string_name is any name that you want to name your string variable and size_of_string is where you define the length of the string, i.e the number of characters strings will store. 

Note that there is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of string which differs strings from normal character arrays. Thus, always declare the size one more in number than the original string that you want to declare. 

Initializing a String:

Like declaration, initialization of strings is way different than any other data type. Because there is not just one, but many ways to initialize your string. Let us look into these different ways by taking examples.

We have considered the string “Cups” to show different initialization methods for initializing a string. 

 Below is an example to declare a string with name as s and initialize it with “Cups”.

  1. char s[] = “Cups”;
  2. Second, char s[40] = “Cups”;
  3. Also, char s[] = {‘C’,’u’,’p’,’s’,‘’\0’’};
  4. Lastly, char s[5] =  {‘C’,’u’,’p’,’s’,‘’\0’’};

Hence, you can see four different ways in which we can initialize the string s[]. You can use either way and it will be fine. But remember to use them according to your requirement. 

Functions related to the Strings in C Programming Language:

Since, strings is a completely different concept in terms of data type, the C Programming language has some built in functions for the application of strings. Because, we use strings in different ways than others. Thus, we have different method of inputs, outputs, addition, etc. 

Therefore, let us go through some important functions related to strings in the C Programming Language. 

gets(): 

In the C programming, gets() is a library function that reads a line from stdin and stores it into the string pointed to by the string variable. However, It will stop when either the newline character is read or when the compiler reaches end-of-file, whichever comes first.

As gets() is a function, it has its unique declaration. Following is the declaration for gets() function.

char *gets(char *str)

Also, it has the following parameter. 

  • str − str is nothing but the pointer to an array of chars where the system stores the C string. 

gets() being a library function has a return value just like other functions. So, the gets() function in C returns the string that we store in the variable on success, and NULL on error or when the end of file occurs, while no characters have been read.

Example

To understand the use of gets() more in an easy way, we have an example. This code below shows the usage of gets() function.

#include <stdio.h>

#include <stdio.h>

int main () {
   char s[50];

   printf("Enter a string : ");
   gets(s);

   printf("Your entered string: %s", s);

   return(0);
}

Output:

Following is the output we get when we execute the code above.

Output for the gets() function.
Output for the gets() function.

fgets():

fgets() is another build in C Library function which The C library function reads a line from the specified stream and stores it into the string pointed to by str. However, it stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

Similar to the gets() function, fgets() also has a unique declaration. Thus, following is the declaration for the fgets() function.

char *fgets(char *str, int n, FILE *stream)

The fgets() function in C has the following parameters:

  • str − str is the pointer to an array of chars where the system reads and stores the string.
  • n − This parameter signifies the maximum number of characters that the system has to read (including the final null-character). Usually, for n we use the length of the array that we pass.
  • stream − stream is nothing but the pointer to a FILE object that identifies the stream where characters are read from. 

The fgets() function returns the same str parameter on success. Also, it returns a null pointer when the compiler reaches the End-of-File or reads no character. Hence, the contents of str remain unchanged and it returns a null pointer.

Additionally, it returns a null pointer if any error occurs.

Example

To understand the usage of fgets() function more clearly, we have come up with the following example. 

#include <stdio.h>

int main () {
   FILE *fp;
   char str[60];
   // opening file for reading
   fp = fopen("file.txt" , "r");
   if(fp == NULL) {
      perror("Error opening file");
      return(-1);
   }
   if( fgets (str, 60, fp)!=NULL ) {
      // writing content to stdout 
      puts(str);
   }
   fclose(fp);
   
   return(0);
}

Output:

Assuming we input the following into the file.txt :

We drink tea and coffee in Cups.

We get the following as the output we get when we execute the code above.

We drink tea and coffee in Cups.

getchar():

This built in function of the C library, gets a character which is an unsigned char from the stdin. We can take it similar to the getc with stdin as its argument.  Declaration

We will declare the getchar() function in the following way such that we can use it appropriately. 

int getchar(void)

The getchar() function has no parameters in its function declaration. 

Since we use the getchar() function to take character inputs. Thus, this function returns the character that the compiler reads as an unsigned char cast to an int or EOF at the end of file or when an error occurs.

Example

Let us understand the usage of getchar() function through the following example.

#include <stdio.h>

int main () {
   char c;
 
   printf("Enter a character: ");
   c = getchar();
 
   printf("You have entered the following character: ");
   putchar(c);

   return(0);
}

Output:

Following is the output we get when we execute the code above.

Output for the getchar() function.
Output for the getchar() function.

puts(): 

puts() is the library function in C Programming Language that writes a string to stdout. But it does not include the null character. However, it appends a newline character for it to display the output. 

The puts() function is basically an output function so it has the declaration as follows. 

int puts(const char *str)

puts() library function has the following parameter

  • str − str is the variable for the C string that we have to write. 

If we execute the puts() function successfully, it returns a non-negative. But, if any error occurs, the puts() function returns EOF which stands for end of file.  

Example

The following example shows the usage of puts() function.

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

int main () {
   char s1[15];
   char s2[15];

   strcpy(s1, "Cups");
   strcpy(s2, "Drink");

   puts(s1);
   puts(s2);
   
   return(0);
}

Output:

Following is the output we get when we execute the code above.

Output for the puts() function.
Output for the puts() function.

putchar():

It is the C Library function for strings which writes a character as an unsigned char which the argument char specifies to the stdout. In other words, it is a puts() function but for characters. 

The putchar() in built C function has the following syntax as its declaration function.

int putchar(int char)

Also, the putchar() has the following parameter:

  • char − it is nothing but the character we have to write. Also, it is the parameter we pass as an int promotion. 

This function of putchar() returns the character which it writes as an unsigned char. But, it casts to an int or EOF if any error occurs.

Example

The small block of code will explain you the proper usage of the putchar() function. 

#include <stdio.h>

int main () {
   char c;

   for(c = 'k' ; c <= 's' ; c++) {
      putchar(c);
   }
   
   return(0);
}

Output:

Following is the output we get when we execute the code above.

Output for the putchar() function.
Output for the putchar() function.

strlen():

Now, the strlen() function is different than any of the functions that we saw earlier. It is the C Programming language library function which computes the length of the string str up to. However it does not include the terminating null character.

We can declare the strlen() function by following the syntax that we have listed below. 

size_s strlen(const char *str)

Parameters

  • str − It is the parameter or variable which is the string. Hence, this is the string that we have to know the length of. In other words, the strlen function will compute the length of the string str.

As you might have guessed, the function strlen() returns the length of the string that you want to find the length of. 

Example

The example that we have stated below will show the usage of strlen() function.

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

int main () {
   char s[80];
   int len;

   strcpy(s, "We use cups to drink tea and coffee");

   len = strlen(s);
   printf("Length of the string |%s| is |%d|\n", s, len);
   
   return(0);
}

Output:

Following is the output we get when we execute the code above.

Output of strlen() function.
Output of strlen() function.

Some additional Functions for Strings in C:

Since strings is a very vast concept, it has several other important functions related to it. You can use these functions in your codes to make them more efficient. So, let us go through some of them briefly. 

  1. strcpy(s1, s2);  It will copy string s2 into string s1.
  2. Second is the strcat(s1, s2); which concatenates string s2 onto the end of string s1.
  3. strcmp(s1, s2); This is a comparison function which will return 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
  4. Next is the strchr(s1, ch); which returns a pointer to the first occurrence of character ch in string s1.
  5. Lastly, strstr(s1, s2);which will return a pointer to the first occurrence of string s2 in string s1.

Wrapping it up:

Hence you are at the post about Strings in C Programming language. In the above post you have learned about strings and all the important functions associated with them. Thus, you are prepared for this topic if they ask you this in an interview or in your college or school level exam. 

Therefore, prepare this topic well and you will be able to attend all questions and coding problems related to this concept. 

Any doubts and queries? Reach out to us below.

Stay tuned for more posts like this!

See you in our next post!

Leave a Comment

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