Strings in C: How to Declare Variable, Initialize, Print, Example

 Strings in C: How to Declare Variable, Initialize, Print, Example

What is String in C?

A String in C is nothing but a collection of characters in a linear sequence. 'C' always treats a string a single data even though it contains whitespaces. A single character is defined using single quote representation. A string is represented using double quote marks.

Example, "Welcome to the world of programming!"

'C' provides standard library <string.h> that contains many functions which can be used to perform complicated operations easily on Strings in C. 

How to Declare and Initialize a String in C

A C String is a simple array with char as a data type. 'C' language does not directly support string as a data type. Hence, to display a String in C, you need to make use of a character array.

The general syntax for declaring a variable as a String in C is as follows,

char string_variable_name [array_size];

The classic Declaration of strings can be done as follow:

 char string_name[string_length] = "string"; 

The size of an array must be defined while declaring a C String variable because it is used to calculate how many characters are going to be stored inside the string variable in C. Some valid examples of string declaration are as follows,

char first_name[15];    //declaration of a string variable
char last_name[15];

The above example represents string variables with an array size of 15. This means that the given C string array is capable of holding 15 characters at most. The indexing of array begins from 0 hence it will store characters from a 0-14 position. The C compiler automatically adds a NULL character '\0' to the character array created.

Let's study the String initialization in C. Following example demonstrates the initialization of Strings in C,

char first_name[15] = "ANTHONY";
char first_name[15] = {'A','N','T','H','O','N','Y','\0'}; // NULL character '\0' is required at end in this declaration
char string1 [6] = "hello";/* string size = 'h'+'e'+'l'+'l'+'o'+"NULL" = 6 */
char string2 [ ] = "world";  /* string size = 'w'+'o'+'r'+'l'+'d'+"NULL" = 6 */
char string3[6] = {'h', 'e', 'l', 'l', 'o', '\0'} ; /*Declaration as set of characters ,Size 6*/

In string3, the NULL character must be added explicitly, and the characters are enclosed in single quotation marks.

'C' also allows us to initialize a string variable without defining the size of the character array. It can be done in the following way,

char first_name[ ] = "NATHAN";

The name of Strings in C acts as a pointer because it is basically an array.

String Input: Read a String

When writing interactive programs which ask the user for input, C provides the scanf(), gets(), and fgets() functions to find a line of text entered from the user.

When we use scanf() to read, we use the "%s" format specifier without using the "&" to access the variable address because an array name acts as a pointer. For example:

#include <stdio.h>
int main() {
char name[10];
int age;
printf("Enter your first name and age: \n");
scanf("%s %d", name, &age); 
printf("You entered: %s %d",name,age);
}

Output:

Enter your first name and age:
John_Smith 48

The problem with the scanf function is that it never reads entire Strings in C. It will halt the reading process as soon as whitespace, form feed, vertical tab, newline or a carriage return occurs. Suppose we give input as "Guru99 Tutorials" then the scanf function will never read an entire string as a whitespace character occurs between the two names. The scanf function will only read Guru99.

In order to read a string contains spaces, we use the gets() function. Gets ignores the whitespaces. It stops reading when a newline is reached (the Enter key is pressed).For example:

#include <stdio.h>
int main() {
char full_name[25];
printf("Enter your full name: ");
gets(full_name);
printf("My full name is %s ",full_name);
return 0;
}

Output:

Enter your full name: Dennis Ritchie
My full name is Dennis Ritchie

Another safer alternative to gets() is fgets() function which reads a specified number of characters. For example:

#include <stdio.h>
int main() {
char name[10];
printf("Enter your  name plz: ");
fgets(name, 10, stdin);
printf("My name is %s ",name);
return 0;}

Output:

Enter your name plz: Carlos
My name is Carlos

The fgets() arguments are :

  • the string name,
  • the number of characters to read,
  • stdin means to read from the standard input which is the keyboard.

String Output: Print/Display a String

The standard printf function is used for printing or displaying Strings in C on an output device. The format specifier used is %s

Example,

printf("%s", name);

String output is done with the fputs() and printf() functions.

fputs() function

The fputs() needs the name of the string and a pointer to where you want to display the text. We use stdout which refers to the standard output in order to print to the screen.For example:

#include <stdio.h>
int main()
{char town[40];
  printf("Enter your town: ");
  gets(town);
  fputs(town, stdout);
  return 0;}

Output:

Enter your town: New York
New York

puts function

The puts function is used to Print string in C on an output device and moving the cursor back to the first position. A puts function can be used in the following way,

#include <stdio.h>
int main() {
char name[15];
gets(name);        //reads a string
puts(name);        //displays a string
return 0;}

The syntax of this function is comparatively simple than other functions.

The string library

The standard 'C' library provides various functions to manipulate the strings within a program. These functions are also called as string handlers. All these handlers are present inside <string.h> header file. 


 

 

Lets consider the program below which demonstrates string library functions:

#include <stdio.h>
#include <string.h>
int main () {
//string initialization
char string1[15]="Hello";
char string2[15]=" World!";
char string3[15];
int val;

//string comparison
val= strcmp(string1,string2);
if(val==0){
    printf("Strings are equal\n");
}
else{
    printf("Strings are not equal\n");
}

//string concatenation
printf("Concatenated string:%s",strcat(string1,string2)); //string1 contains hello world!

//string length
printf("\nLength of first string:%d",strlen(string1));
printf("\nLength of second string:%d",strlen(string2));

//string copy
printf("\nCopied string is:%s\n",strcpy(string3,string1));  //string1 is copied into string3
return 0;
}

Output:

Strings are not equal
Concatenated string:Hello World!
Length of first string:12
Length of second string:7
Copied string is:Hello World!

Other important library functions are:

  • strncmp(str1, str2, n) :it returns 0 if the first n characters of str1 is equal to the first n characters of str2, less than 0 if str1 < str2, and greater than 0 if str1 > str2.
  • strncpy(str1, str2, n) This function is used to copy a string from another string. Copies the first n characters of str2 to str1
  • strchr(str1, c): it returns a pointer to the first occurrence of char c in str1, or NULL if character not found.
  • strrchr(str1, c): it searches str1 in reverse and returns a pointer to the position of char c in str1, or NULL if character not found.
  • strstr(str1, str2): it returns a pointer to the first occurrence of str2 in str1, or NULL if str2 not found.
  • strncat(str1, str2, n) Appends (concatenates) first n characters of str2 to the end of str1 and returns a pointer to str1.
  • strlwr() :to convert string to lower case
  • strupr() :to convert string to upper case
  • strrev() : to reverse string

Converting a String to a Number

In C programming, we can convert a string of numeric characters to a numeric value to prevent a run-time error. The stdio.h library contains the following functions for converting a string to a number:

  • int atoi(str) Stands for ASCII to integer; it converts str to the equivalent int value. 0 is returned if the first character is not a number or no numbers are encountered.
  • double atof(str) Stands for ASCII to float, it converts str to the equivalent double value. 0.0 is returned if the first character is not a number or no numbers are encountered.
  • long int atol(str) Stands for ASCII to long int, Converts str to the equivalent long integer value. 0 is returned if the first character is not a number or no numbers are encountered.

The following program demonstrates atoi() function:

#include <stdio.h>
int main()
{char *string_id[10];
  int ID;
  printf("Enter a number: ");
  gets(string_id);
  ID = atoi(string_id);
   printf("you enter %d  ",ID);
  return 0;}

Output:

Enter a number: 221348
you enter 221348
  • A string pointer declaration such as char *string = "language" is a constant and cannot be modified.

Summary

  • A string is a sequence of characters stored in a character array.
  • A string is a text enclosed in double quotation marks.
  • A character such as 'd' is not a string and it is indicated by single quotation marks.
  • 'C' provides standard library functions to manipulate strings in a program. String manipulators are stored in <string.h> header file.
  • A string must be declared or initialized before using into a program.
  • There are different input and output string functions, each one among them has its features.
  • Don't forget to include the string library to work with its functions
  • We can convert string to number through the atoi(), atof() and atol() which are very useful for coding and decoding processes.
  • We can manipulate different strings by defining a array of strings in C.

 

 

 

Post a Comment

0 Comments