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. A 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 4
Write a program that inputs a string and displays it as triangle.
For example, if the user enters World, the program displays the following:
W
W o
W o r
W o r l
W o r l d
#include<iostream>
#include<string.h>
using namespace std;
main()
{
char str[100];
int i, j, len;
cout<<"Enter a string:";
cin.getline(str, 100);
len = strlen(str);
for(i=0; i<len; i++)
{
for(j=0; j<=i; j++)
cout<<str[j];
cout<<endl;
}
}
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);