Learning C/C++ Step-By-Step - Page 8

08. Step-by-Step C/C++ --- C Programming - Strings



  - Introduction
  - Characteristics of a strings
  - Operations on Strings
            1. Definition of Strings
          2. Initialization of Strings
          3. Reading and printing of Strings
          4. Reading Embedded Blanks
          5. Length of a String
          6. Strings and Functions
          7. Array of Strings



Arrays are used to examine strings, generally strings are of array type variables.
A string is a collection of characters including space where as word is a collection of characters excluding space. Every string variable must be terminating with ‘\0’ null character and the index value is starts with 0.

Every string has the following characteristics:

 1. It must be a collection of characters (i.e. characters, numbers, and special characters).
2. Every string must be ends with a NULL character ( i.e. ‘\0’ )
3. A unique positive number called index identifies each character of a string.
4. Index value must be starts with 0.
5. Random access on characters in a string is possible.
6. A string must be declared with its fixed size like arrays.

For Example consider the following example:

char str = " magic";


A variety of string library functions are used to manipulate strings. An array of strings is an array of arrays of type char.


Operations on Strings

We can perform much better operations than using Library string functions.
Strings can accept the following operations.

            1. Definition of Strings
          2. Initialization of Strings
          3. Reading and printing of Strings
          4. Reading Embedded Blanks
          5. Length of a String
          6. Strings and Functions
          7. Array of Strings

1. Definition of a String

Every variable must be declared at the beginning of the program.
Definition of string variable is as follows.


2. Initialization of Strings

Strings can be initialized in the following methods.

  1. Direct Assignment

char name[10] = "Ashitha";

Assigns "Ashitha" to name rest of the place left blank.
2. Direct Assignment without Size

char name[] = "Ashitha";

Assigns "Ashitha" to name and fix it’s width up to the size of Constant.
  3. Design time Assignment

char name[10];
strcpy(name, "Ashitha");

Using Strings functions it is possible.
But C never support the assignment like :
name = "Ashitha";
4. Runtime Assignment

char name[10];
scanf("%s", name);

It accepts and assigns constant value to variable at runtime.

3. Reading and Printing Strings

C provides various types of string functions to read and print a string constant. Listed below.

 Input Statements
Output Statements

 /* Program to accept and display a string */

/* 51_strings.c */
#include <stdio.h>
int main()
     char str[20];
     scanf("%s", str);
     printf("%s" str);
     return 0;

 /* Program to accept and display a string with a prompt */

/* 52_strings.c */
#include <stdio.h>
int main( )
     char str[20];
     printf("Enter a string :"); scanf("%s", str);
     printf("\nYou entered : %s", str);
     return 0;


4. Reading embedded blanks

scanf Accepts string, thus it will read strings consisting of a single word, but anything typed after a space is thrown away.

Eg. Enter String : Law is a bottomless pit.
You entered : Law

To read text containing blanks we use another function, gets().

 /*read string with embedded blanks */

/* 53_gets.c */
const int MAX = 80;
int main()
     char str[MAX];
     print("Enter a string :"); gets(str);
     printf("You entered :"); puts(str);
     return 0;

5. Length of String

Every string has its fixed length depending on its constant.
The following program demonstrates, How to find the length of the string

 /* To find the length of a given string */

/* 53_length.c */
#include <stdio.h>
int main()
     int i=0;
     char str[50];
     printf("Enter a string "); gets(str);
     while(str[i] != '\0') i++;
     printf("Length is %d", i);
     return 0;

6. Strings and Functions

A function is a self-contained block of statements that perform a specific task. The best way to organize strings.
The following are the example of string organization using functions.

  /* Program to find the length of a string */

/* 54_len.c */
#include <stdio.h>
int len_str(char s[]);

int main()
     int l; char str[50];
     printf("Enter a string "); gets(str);
     l = len_str(str);
     printf("\nLength of string : %d", l);

int len_str(char s[])
     int l=0;
     while(s[l] != '\0') l++;
     return l;

 /* Program to accept and print a string */

/* 55_str.c */
#include <stdio.h>
void disp_str(char s[]);

int main()
     char str[50];
     printf("Enter a string "); gets(str);
     return 0;

void disp_str(char s[])
     int i=0;
     while( s[i] != '\0' ) putch(s[i++]);

7. Array of Strings

Arrays are used to examine strings, generally strings are of array type variables. So, we can access array of strings.
The following examples illustrate, How Array of Strings organized.

  /* Program to display an array of strings */

/* 56_display.c */
#include <stdio.h>
void main()
     char week[7][] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
     int i;
     for( i = 0; i<7; i++) puts(week[i]);

 /* Program to accept and display an array of strings */

/* 57_strings.c */
#include <stdio.h>
void main()
     char names[7][10]; int i;
     for( i = 0; i<7; i++) gets(names[i]);
     for( i = 0; i<7; i++) puts(names[i]);

Share this page:

19 Comment(s)

Add comment


From: at: 2009-01-09 15:11:23

The tutorial looks so great. But I have some doubts. Why do you use "clrscr()" function and conio.h library, if you are using the C/C++ standard? (I found that in the pages number 4 and 5, but that is as far as i got).

From: at: 2009-01-20 16:25:53

I tried to lead learners from learning C to C++, so the pages 4 and 5 reflects most of the usage of C language, so it introduces users to learn about other header files.

From: Shantanu Goel at: 2009-01-08 04:44:05

Great tutorial Ganesh. And here is a link for people who finish your tutorial and want to learn a bit about how to make their code secure and optimized: Safer Code - Secure Coding in C/C++ This has a lot of stuff regularly published to cater to various security and performance related issues with C/C++ and anyone can follow it easily at a gradual pace.

From: Anonymous at: 2010-02-01 06:01:52

Very nice!

From: pickatutorial at: 2010-10-09 12:52:44

Great Work. Keep it up.

From: TodaysTech at: 2011-07-12 21:31:29

If anyone is interested, I have an ongoing blog that is covering the transition from the Business world to the Programming world.  Since it's from my own perspective, I think it can be easy to read and relate to for most first timers.


From: Crosility at: 2012-12-06 23:44:36

In the chart, it says 'vhar', not 'char'.

From: Jason at: 2013-04-16 14:58:31

Why using conio.h ?   It is not part of C standard, C++ standard, nor is it part of any Linux or Unix libraries.  

The inclusions of Microsoft specific libraries in chapters 4 & 5 have me doubting the validity the rest of the tutorial (learning c/cpp on Linux).

The tutorial is well written, however,  but I think it would be more appropriate on a .Net or Msdn blog. 

Thanks Ganesh!

From: Anonymous at: 2009-09-01 11:56:38


\* 0001_hello.c *\ and  \* 0001_hello.cpp *\


/* 0001_hello.c */ and /* 0001_hello.cpp */



From: Scott_R at: 2012-01-03 22:24:55

The numbering for the examples is off by one.

For example:

"10. Write a program to find the total and average marks of a student"

/* 11_stud.c */

From: Erica at: 2012-12-31 19:56:21

In 11_stud.c

avtg = total / 3;

should be

avg = total / 3;

Also the clrscr() function won't compile in g++. If others need you can add // to the start of the line and the line will become a comment.

From: Bob at: 2011-09-09 12:50:09

Ex 13 :

  if ( age >= 13 and age <= 19 ) printf("Teen Age");
  if ( age >= 20 and age <= 35 ) printf("Young Age");
  if ( age >= 36 and age < 50 ) printf("Middle Age");

should read as :

      if ( age >= 13 && age <= 19 ) printf("Teen Age");
      if ( age >= 20 && age <= 35 ) printf("Young Age");
      if ( age >= 36 && age < 50 ) printf("Middle Age");

From: Anonymous at: 2009-06-25 12:57:51

Example 14 would be less ....rectangular and much more triangular if, instead of

for (j=1;j<=5;j++)

one had

for (j=i; j<=5;j++)

From: Snehal at: 2009-06-15 07:00:15

In the difference between union and structure ,the names are misplaced ...means in union , structure points are placed and viceversa... Make it correct

From: bzero in c programming at: 2014-07-30 10:54:51


There is a bug in the number 4 example. You will get compilation error while running this program you will get a compilation error like below:

 binaryover.cpp:31:11: error: expected ‘;’ before ‘t1’

binaryover.cpp:32:6: error: ‘t3’ was not declared in this scope

binaryover.cpp:32:11: error: ‘t1’ was not declared in this scope

binaryover.cpp:32:16: error: ‘t2’ was not declared in this scope

Because you are using "using namespace std;" but in the standard library there is a function named time (). So, to solve the problem, you can change the name of the function time ()  to any other name like time1 (), then you will be able to run your code without any error. 

From: Abhijeet at: 2009-01-11 01:25:52

Though i haven't done it myself, mingw32 can create win32 executables from linux. As its description says "Minimalist GNU win32 (cross) compiler, A Linux hosted, win32 target, cross compiler for C/C++, Freedom through obsolescence. Those who still really need to can now build windows executables from the comfort of Debian." You could check it out.

From: Paul at: 2009-01-07 22:40:39

Thanks, this is a nice tutorial, I'm actually a php programer and I saw a lot similar with php's language, but I have a question:

Can I compile a c++ program under linux to make a .exe to run on windows and viceversa?

And how to do that if it is possible?

From: dbrion at: 2009-06-30 11:58:40

"Can I compile a c++ program under linux to make a .exe to run on windows "

Yes :

I confirm the last post and cross compilers can natively be found with recent Fedora (and any linux distribution, messeems!) The way all the stuff necessary could be downloaded and made working can be found with adaptations of :


(one just has to stop at "make xtools": they are downloaded and put into a proper place).

Else, if you like linux and have "only"  Windows, you can use cygwin (avoids dualbooting or switching to another computer)  with the sources (it is very rare that sources need to be different between both systems, they use the same compiler -gcc/g+++- and almost the same include file names.... ) ...


"and viceversa"

No (not because linux executables do not have a .exe suffix!):

 but you can edit/compile/test your program(s) under cygwin (google search can find it) until it works and port it (i.E the source, the compilation  and test scripts) to Linux (there is almost no effort, apart the efforts linked with different disk nomenclatures, of course).

 Else, unless emulating linux with vmplayer/qemu/vbox -all these emulators are Windows ported-? but it is more complicated than C/C++....

From: Iftekhar Ahmed at: 2010-05-14 19:31:55


Its relly helpful, I have 48 Hrs for my Exams..........................

Thanks for posting ............


Iftekhar Ahmed