LERAN C PROGRAMMING

Learn one of the most powerful programming languages in the world and become a rockstar developer.

Strings


In this tutorial, you'll learn about strings used in c programming.

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’.

Declaration of strings

Declaring a string is as simple as declaring a one dimensional array. Below is the basic syntax for declaring a string.

char str_name[size];

In the above syntax str_name is any name given to the string variable and size is used define the length of the string, i.e the number of characters strings will store. Please keep in mind that there is an extra terminating character which is the Null character (‘\0’) used to indicate termination of string which differs strings from normal character arrays.

Initializing a String

A string can be initialized in different ways. We will explain this with the help of an example. Below is an example to declare a string with name as str and initialize it with “GeeksforGeeks”.

char str[] = "Adzetech";
char str[30] = "Adzetech";
char str[] = {'A', 'd', 'z', 'e', 't', 'e', 'c', 'h', '\0'};
char str[9] = {'A', 'd', 'z', 'e', 't', 'e', 'c', 'h', '\0'};

Let us now look at a sample program to get a clear understanding of declaring and initializing a string in C and also how to print a string.

// C program to illustrate strings 
  
#include<stdio.h>
  
int main() 
{    
    // declare and initialize string 
    char str[] = "Adzetech"; 
      
    // print string 
    printf("%s",str); 
      
    return 0; 
} 
Output :
Adzetech

Passing strings to function

As strings are character arrays, so we can pass strings to function in a same way we pass an array to a function. Below is a sample program to do this:

// C program to illustrate how to  
// pass string to functions 
#include<stdio.h>
  
void printStr(char str[]) 
{ 
    printf("String is : %s",str); 
} 
  
int main() 
{    
    // declare and initialize string 
    char str[] = "Adzetech"; 
      
    // print string by passing string 
    // to a different function 
    printStr(str); 
      
    return 0; 
} 
Output :
String is : Adzetech


Previous Next
x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine