String Handling Programming Exercise 1 in C/C++

What is String in C/C++?

String can be defined as the combination of characters. String handling is used to manipulate strings such as finding number of characters in a file or comparing two files. String are commonly used with file handling.

File is a sequence of bytes. Input and output streams are used to store and retrieve strings in file.

Syntax of String

Data_type var_name[length];

For example

char name[40];

In above statement we declare a variable name with length of 40 characters.

This variable occupies 40 bytes in memory.

One character occupies one byte in memory.

In other words, if we want to store a single character in computer we require one byte.

Exercise Question 1

Write a program that inputs a number from user and checks the string is a palindrome or not. A palindrome is a string that reads the same backwards as forwards such as MADAM and MOM.


#include<iostream>
#include<string.h>
using namespace std;

main()
{
	char s1[100], s2[100];
	cout<<"Enter a string:";
	cin.getline(s1, 100);
	strcpy(s2, s1);
	strrev(s2);
	if(strcmp(s1, s2) == 0)
	cout<<"The string is palindrome:";
	else
	{
		cout<<"The string is not palindrome:";
	}
}

Following Functions are commonly used in String Handling

getline() Function

getline function is used to input a string from user. following is the syntax of this function

getline(string,length);

strcpy() Function

strcpy() function is used to copy a string. Following is the syntax

strcpy(string1,string2);

strrev() Function

This function is used to reverse a string. 

Syntax:

strrev(string);

strcmp() Function

This Function is used to compare two strings.

Syntax:

strcmp(string1,string2);

Leave a Reply