What is Strings in C ?

By Shakib Ansari | Date: Fri, May 9, 2025

Ek string, characters ka sequence hoti hai jisko single data item ki tarah treat karte hai. Any group of characters (except double quote sign) ek string hoti hai agar wo double quotation se enclosed hai. Example: "Man is obviously made to think."

Agar ham string mein double quote ko include karke print karna chahte hai to hame back slash '' use karna padega. Example: "" Man is obviously made to think, " said Pascal." this look " Man is obviously made to think, " said pascal. printf("" Well Done !""); -> " Well Done !".

Character strings ka use meaningful and readable programs ko build karne ke liye hota hai. Character strings par kuch common ye operations hote hai:

  • Reading aur writing strings.
  • Strings ko sath mein combine karna.
  • Ek string ko dusri mein copy karna.
  • Strings ki equality ko check karne ke liye compare karna.
  • String ke ek portion ko extract (nikalna) karna.

Is blog mein, ham inhi operations ko discuss aur string ke library functions ko implement karenge.

Declaring and Initializing String Variables

C language, string data type ko support nhi karti. Lekin ye hame character array ko string ki form mein represent karna allow karti hai. Isliye C, mein ek string variable koi bhi ek C variable name ho sakta hai aur ye hamesha character array ki tarah declare hota hai.

Example: char string_name[size];

The size, number of characters specify karta hai in the string_name. Some Examples Are:

char city[10];

char name[30];

Jab compiler ek character array ko compile karta hai to ye, us character array ke end mein automatically ek null character ('') supply kar deta hai jo ki ek string ki identity hoti hai. Isliye string ka size maximum number of characters + 1 hota hai. Hame hamesha iske liye 'size+1' specify karna chahiye, 1 for null character ke liye.

Example: char city[6] = "Delhi"; // Correct

char city[5] = "Delhi"; // Incorrect. Not enough space for ''.

Ham string ko do tareeko se initialize kar sakte hai normal character array aur directly string format.

Example: char name[11] = "Beyond Man";

char name[11] = {'B', 'e', 'y', 'o', 'n', 'd', ' ', 'M', 'a', 'n'}.

name ek 11 character long array ya string hai kioki 10 character for "Beyond Man" and 1 character for null '' terminator. C language, mein character array ko ham bina size specify kare bhi use kar sakte hai. Aise cases mein array ka size automatically calculate ho jata hai based on number of elements.

For Example: char string[] = {'G', 'O', 'O', 'D', ''};

Yaha par string array five element ka array hai, kioki 1 for null.

Ham array ke size ko initializer ke size se bhi large declare kar sakte hai. For Example: char str[10] = "GOOD"; Ye string ko declare karne ka ek valid tareeka hai. Is case mein, computer character array create karega of size 10, aur value "GOOD" ko place kar dega, aur ise null character se terminate kar dega aur others elements ko NULL se initialize kar dega. The storage will look like:

| G | O | O | D | | | | | |

String ki kuch aisi declaration hai jo ki sahi lagti hai lekin wo wrong jaise, char str2[3] = "GOOD", ye ek compile time error hai kioki array size '3' hai aur value ka size 4+1 hai. Note that ham initialization aur declaration ko separate bhi nhi kar sakte,

For Example: char str3[5];

str3 = "GOOD";

is not allowed. Similarly, char s1[4] = "abc"

char s2[4];

s2 = s1; /* Error */

ye allow nhi. Ek array kabhi bhi assignment operator '=' se assign nhi ho sakta.

Terminating Null Character

In C, string ek simple character array hota hai jo ki ends hota ek special null character ''se. Ye null terminator batata hai ki string kahaan khatam ho rahi hai, warna C ko string ka end nahi pata chalega. Saare string functions jaise printf, strlen, strcpy etc., isi '' pe depend karte hain to stop reading characters. Agar hum '' nahi denge, toh program garbage memory read kar sakta hai ya crash ho sakta hai. Isiliye, hamesha string banate waqt ek extra space '' ke liye dena zaroori hota hai.

Reading Strings From Terminal

Using scanf Function: Input function scanf ka use %s format specifiaction mein ho sakta hai to read string of characters. Example:

char address[10]

scanf("%s", address);

Yaha ek scanf function ke saath ek problem hai, jab bhi first white space ham enter karte hai to ye input ko terminate kar deta hai. Ek white space, blanks, tabs, carriage returns, form feeds, and new lines ho sakti hai. Isliye agar ham kisi line of text ko type kare terminal par jaise ki, NEW DELHI to sirf array address NEW ko hi input lega aur blank space hone ki wajah se input ko terminate kar dega. Agar ham puri line ko input lena chahte hai to, hame two character arrays banane padenge.

char adr1[4], adr[6];

scanf("%s %s", adr1, adr2); ab yaha par adr1 ko NEW aur adr2 ko DELHI assign ho jayega.

Reading a Line of Text

Hamne abhi tak scanf() function dekha with %s ke saath ye sirf strings ko without white spaces ke read karta hai. Isliye iska use aise text ko lene ke liye nhi ho sakta jo more then one word hai. However, C supports a format specification jo ki edit set conversion code %[..] hota hai isko ham ek line ko read karne ke liye use karte hai jisme variety of characters ho sakte hai, including whitespaces.

The Code:

char line[80];

scanf("%[^ ]", line);

printf("%s", line);

Ye ek line of input ko keyboard se read karega aur display karega same as on the screen. Ham is method ko bahut hi rarely use karte hai, kioki C support karta hai ek intrinsic function ko is kaam ko karne ke liye. Jaise,

Using getchar and gets Functions

Ham getchar function ka use ek character ko input lene ke liye karte hai aur ham iska use string ko input lene ke liye bhi kar sakte hai. Isme ham har baar ek single character input lenge aur phir usko array mein place kar denge, isse ham ek array mein poori line ko read aur store kar sakte hai. Character reading ko ham tab terminate kar denge jab newline character (' ') enter hoga aur phir string ke end mein null character ko insert kar denge. The getchar function call takes the form:

char ch;

ch = getchar();

getchar function mein koi parameters pass nhi karte hai.

Program to read a line of text from the terminal.

#include <stdio.h>
int main(int argc, char const *argv[])
{
    char line[81], character;
    int c = 0;
    printf("Enter text. Press <Return> at end");
    do
    {
        character = getchar();
        line[c] = character;
        c++;
    } while (character != '\n');
    c = c - 1;
    line[c] = '';
    printf("%s", line);
    return 0;
}
Output:
Enter text. Press <Return> at end
Success comes after failure...
Success comes after failure...

Explanation: Ye program ek text ki line read karega (up to a maximum of 80 characters) string line mein using getchar function. Har baar ek character read hoga aur wo apni jagah string line mein insert ho jayega aur phir ye newline character (' ') ke liye test karega. Jab newline character read hoga hoga (signalling the end of line), tab reading loop terminate ho jayegi aur newline character null character se replace ho jayega aur ye string mein end of character ko indicate karega. Jab loop exit ho jayegi, to index value c ek number zyada hogi string ke last character se isliye the index value c-1 wo position hogi jaha par null character store hoga.

Ek another aur convenient method string ko read karne ka gets function hota hai, aur ye whitespaces ko bhi contain kar sakta hai. Ye function <stdio.h> header file mein hota hai. Ye ek simple function hota hai jo ek string ko as a parameter leta hai. Example: gets(str);

Program to copy one string inoto another and count the number of characters copied.

#include <stdio.h>

int main(int argc, char const *argv[])
{
    char string1[80], string2[80];
    printf("Enter a string :");
    int i;
    scanf("%s", string2);
    for (i = 0; string2[i] != ''; i++)
        string1[i] = string2[i];
    string1[i] = '';
    printf("\n");
    printf("%s\n", string1);
    printf("Number of characters = %d\n", i);
    return 0;
}
Output:
Enter a string : BeyondMan

BeyondMan
Number of characters = 9

Explanation: Ye program pehle string2 ko input lega using scanf() function, aur phir for loop mein har character ko character by character string1 mein store kar dega. Loop terminate hone ke baad ye string1[i] (last index) par null '' character ko store kar dega. End mein ye printf() function se string1 aur Number of character ko print kar dega.

Using putchar and puts Functions

Like getchar, C ek aur character handling function ko support karti hai which is putchar iska use character variable ko output karne ke liye hota hai.

Example: char ch = 'A';

putchar (ch); Ye function putchar ek parameter require karta hai. This statement is equivalent to:

printf("%c", ch);

String ko output karne ke liye ham is function ko loop mein repeatedly use karke ek array ko character by character print kar sakte hai

Example:

char name[6] = "Paris";
for(int i = 0; i < 5; i++)
     putchar(name[i]);
putchar('\n');

Another aur more convenient method puts hai jo string ki values ko print karta hai. puts method <stdio.h> header file mein hota hai. Ye ek parameter function hota hai. puts(str);

Example of using gets and puts

#include <stdio.h>
int main(int argc, char const *argv[])
{
    char line[40];
    gets(line);
    puts(line);
    return 0;
}
Output:
I Am Beyond Man...
I Am Beyond Man...
About the Author

Hi, I'm Shakib Ansari, Founder and CEO of BeyondMan. I'm a highly adaptive developer who quickly learns new programming languages and delivers innovative solutions with passion and precision.

Shakib Ansari
Programming

Comments