Home Previous year paper Algorithms Notes About us

Quick Links

Data Structure

Advanced Data Structure

Algorithms

String

In programming, a String is used as a datatype just like int or float might be used; however, the difference here is that, String deals with textual kind of data. It can consist of alphabets, numbers, spaces and special characters. Strings are often enclosed in double quotation marks(“This is a String”). Strings can be thought of as a thread connecting various letters as shown below.

C-strings

In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).

Syntax

char str[] = "C++";

Alternative ways of defining a string

char str[4] = "C++";
char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};

#include
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}

Library Function for String Using Manipulation

strcat

This function is used for concatenation which means it combines two strings. Using this function, a specified source string is appended to the end of a specified destination string. On success, this function returns a reference to the destination string; on failure, it returns NULL.

char *strcat(char *destination, const char *source) ;

strlen

The length of a string is returned by this function, excluding the null character at the end. That is, it returns the string's character count minus 1 for the terminator.

size_t strlen(const char *string);

strcpy

strcpy copies a string from the source string to the destination string, including the null character terminator. The return value of this function is a reference to the destination string.

char *strcpy(char *destination, const char *source) ;

strcmp

This function joins two strings together. It returns a value less than zero if the second string is greater. It returns a number greater than zero if the first string is greater than the second. It returns 0 if the strings are equivalent.

int strcmp(const char *str1, const char *str2) ;

Arrays of String

An Array of String is an array that stores a fixed number of values that are of the String data type.
Array of String in C/C++:

char strarr[m][n]

Passing String to Functions

// Declaring a String
char str[5]="Hello";
// Passing string to Function
func(str);

Practice Problems On Strings