C Programming Tutorial – Strings

A string constant is an array of characters just like an array of integers. It helps to work with words and sentences in C programming. Yet, an array of integers and character array are not the same.

Learn basic of C programming before you begin with strings. If you are familiar with the C basics continue reading.

  1. C Program Structure.
  2. C Printing Output.
  3. C Reading Input Values.
  4. C Data Types.
  5. C Arrays.

What is a String constant?

A string constant is a one-dimensional array of characters with is terminated by ‘\0’, also called a null character.

char firstname[] = { 'P', 'E', 'T', 'E', 'R', '
char firstname[] = { 'P', 'E', 'T', 'E', 'R', '\0'};
'};

The value of a Null character is 0 and each character in the string constant occupy  1 byte of memory. The syntax to initialize a string is very simple.

char name[] = "Rajesh";

where

char = data type of string.

name[]    = indicates that it is a character array or a string.

"   "   =  double quotes show that the value is a string.

Rajesh     = actual string value.

The C compiler inserts a ‘\0’ automatically, so there is no need to specify null for every string that you create.

String Constant Memory Representation

String Constant Memory Representation

Reading and Printing String Constant

Reading input and writing out is an important part of the C programming language. To read a string constant use following syntax.

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

You already know that name[10] is declared as a string of type char. The scanf() is a builtin function that read inputs of various data types. To tell scanf() that the input is a string use the modifier “%s”. But, scanf() can only read a single word like “Rajesh”, and not “Rajesh Kumar”.

To read a multi-word string use gets() or do following.

scanf("%[^\n]s", name);

The modifier is used for printing strings. For example,

printf("%s", name);

String Example Program

It is time to implement everything you learned so far about strings. In this C program,  you will perform two tasks.

  1. read and print a single word string.
  2. read and print a multi-word string.

Program Code

#include <stdio.h>

#include <string.h>

int main()

{

char input_name[35];

int choice;

/* Menu */

printf("Menu\n\n");

printf("1. Read Single Word\n");

printf("2. Read Multi-Word String\n");

printf("\n\n Enter your Choice:");

scanf("%d",&choice);

switch(choice)

{

case 1: 

    system("cls");

    printf("Enter Single Word:");

    scanf("%s", &input_name);

    printf("%s", input_name);

    break;

case 1:

    system("cls");

    printf("Enter Multi-Word:");

    scanf("%[^\n]s", &input_name);

    printf("%s", input_name);

    break;

}

system("pause");

return 0;

}

Output

Output - String Program

Output – String Program

Related Articles:-