String Handling Programming Exercise 5 in C/C++

What is String in C/C++?

The string can be defined as the combination of characters. String handling is used to manipulate strings such as finding a number of characters in a file or comparing two files. The string is 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 the above statement, we declare a variable name with a 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 5

Write a program that inputs a string and a character. It converts
each occurrence of the given character in the string to opposite case.

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

main()
{
	char ch, c, str[100];
	int i, j, len;
	cout<<"Enter a string:";
	cin.getline(str, 100);
	cout<<"Enter a character:";
	cin>>ch;
	len = strlen(str);
	for(i=0; i<len; i++)
	{
	if(toupper(str[i]) == ch || tolower(str[i]) == ch)
		{
			c = str[i];
			if(c>=65 && c<=90)
			  c = c + 32;
			else if(c>=97 && c<=122)
			  c = c - 32;
		    str[i] = c;  
		}
	}
	cout<<str;
}

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);

Related Posts