String in C++

Page Contents:

Definition of String in C++?
Initializing string
String Assignments
Concatenate Two Strings Without Using String Function (That Is: Strcat())
String-handling library in C++

Definition of String in C++?

A string is a series of characters treated as a single unit. A string may include letter digits and various special characters such as +,-,*,/ and $. String literals, or string constants, in C++ are written in double quotation as given below:

"Welcome home"
"How are you?"
"I am fine"

A string in C++ is an array of characters ending in the null character(‘\0’), which specifies where the string terminates in memory

Initializing string

A string, that is, an object belonging to the string class can be initialized when you define it using

  • A predefined string constant
  • A certain number of characters
  • A predefined string or part of a string.

String Assignments

When you assign a value to a string, the current contents are replaced by a new character sequence. You can assign the following to a string object

  • Another string
  • A string constant or
  • A single character

concatenate two strings without using String Function (that is: strcat())

You can use the (+) operator to concatenate strings, that is, to join two or more strings together.

For example:

string sum, s1("Hello!"), s2("How are you ?"); 
sum = s1 + s2;

OUTPUT:

Hello! How are you ?

By using + operator will form an expression of the string type

Not allocating sufficient space in a character array to store the null character that terminates a string is an error

Passing a string as an argument to a function when a character is expected is a syntax error

Creating or using a “string” that does not contain a terminating null character is an error

String-handling library in C++

The string-handling library provides many useful functions for manipulating string data, comparing string, searching a string for characters and other strings, tokenizing strings and determining the length of strings. The prototypes for these functions are located in the header file <cstring>

Error comes when you do this

Forgetting to include the <cstring> header file when using functions from the string handling library causes compilation errors.

Function prototypeFunction description
char *strcpy(char*s1,const char*s2); Copies the string s2 into the character array s1.The value of s1 is returned
char *strncpy(char*s1,const char *s2,size_t n); Copies at most n characters of the string s2 into the character array s1.The value of s1 is returned
char *strcat(char*s1,const char*s2); Appends the string s2 to the string s1.The first character of s2 overwrites the terminating null character of s1.The value of s1 is returned.
char *strncat(char*s1,const char*s2,size_t n); Appends at most n characters of string s2 to string s1.The first character of s2 overwrites the terminating null character of s1.The value of s1 is returned.
int strcmp(const char*s1,const char*s2);Compares the string s1 with the string s2.The function returns a value of zero,less than zero or greater than zero if s1 is equal to ,less than or greater than s2, respectively.
char *strtok(char *s1,const char*s2); A sequence of calls to strtok breaks string s1 into “tokens” logical pieces such as words in a line of text delimited by characters contained in string s2.The first call contains s1 as the first argument, and subsequent calls to continue tokenizing the same string contain Null as the first argument.A pointer to the current token is returned by each call.If there are npo more tokens wjhen the function is called,Null is returned.
size_t strlen(const char *s); Determines the length of string s.The number of characters preceding the terminating null character is returned.

Here are Few Programs regarding Function library

Copying Strings with strcpy and strncpy

Function strcpy copies its second argument a string into its first argument a character array that must be large enough to store the string and its terminating null character. Function strncpy is equivalent to strcpy, except that strncpy specifies the number of characters to be copied from the string into the array.

#include<iostream>
using std::cout;
using std::endl;
#include<cstring>
int main()
{
char x[]="Happy Birthday to You";
char y[25];
char z[15];
strcpy(y,x);
cout<<"The string in array x is:"<<x
    <<"\n The string in array y is:"<<y<<'\n';
strncpy(z,x,14);
z[14]='\0';
cout<<"The string in array z is:"<<z<<endl;
return 0;
}

OUTPUT:

The string in array x is:Happy Birthday to You
The string in array y is:Happy Birthday to You
The string in array z is:Happy Birthday

Concatenating Strings with strcat and strncat

Function strcat appends its second argument(a string) to its first argument(a character array containing a string).The first character of the second argument replaces the null character(‘/0’) that terminates the string in the first argument.The programmer must ensure that the arrary used to store the first string is large enough to store the combination of the first string, the second string and the terminating null character(copied from the second string).Function strncat appends a specified number of characters from the second string to the first string and appends a terminating null character to the result.

Comparing Strings with strcat and strncat

#include<iostream>
using std::cout;
using std::endl;
#include<cstring>
int main()
{
char s1[20]="Happy";
char s2[]="New Year";
char s3[40]=" ";
cout<<"s1= "<<s1<<"\ns2="<<s2;
strcat(s1,s2);
cout<<"\n\nAfter strcat(s1,s2):\ns1"<<s1
   <<"\ns2="<<s2;
strncat(s3,s1,6);
cout<<"\n\nAfter strncat(s3,s1,6):\ns1="<<s1
    <<"\ns3="<<s3;
strcat(s3,s1);
cout<<"\n\nAfter strcat(s3,s1):\ns1"<<s1
    <<"\ns3="<<s3<<endl;
return 0;
}

OUTPUT:

s1= Happy
s2=New Year
After strcat(s1,s2):
s1HappyNew Year                                                                    s2=New Year
After strncat(s3,s1,6):                                                            s1=HappyNew Year                                                                   s3= Happy
After strcat(s3,s1):
s1=HappyNew Year
s3=HappyNHappyNew Year 

Comparing String with strcmp and strncmp

#include<iostream>
using std::cout;
using std::endl;
#include<iomanip>
using std::setw;
#include<cstring>
int main()
{
char *s1="Happy New Year";
char *s2="Happy New Year";
char *s3="Happy New Year";
cout<<"s1="<<s1<<"\ns2="<<s2
    <<"\ns3="<<s3<<"\n\nstrcmp(s1,s2)="
    <<setw(2)<<strcmp(s1,s2)
    <<"\nstrcmp(s1,s3)="<<setw(2)
    <<strcmp(s1,s3)<<"\nstrcmp(s3,s1)="
    <<setw(2)<<strcmp(s3,s1);
cout<<"\n\nstrncmp(s1,s3,6)="<<setw(2)
    <<strncmp(s1,s3,6)<<"\nstrncmp(s1,s3,7)="
    <<setw(2)<<strncmp(s1,s3,7)
    <<"\nstrncmp(s3,s1,7)="
    <<setw(2)<<strncmp(s3,s1,7)<<endl;
return 0;
}

OUTPUT:

s1=Happy New Year
s2=Happy New Year
s3=Happy Holidays

strcmp(s1,s2)=0
strcmp(s1,s3)=1
strcmp(s3,s1)=-1

strncmp(s1,s3,6)=0
strncmp(s1,s3,6)=1
strncmp(s3,s1,7)=-1

Tokenizing a String with strtok

Function strtok breaks a string into a series of tokens. A token is a sequence of characters separated by delimiting characters(usually spaces or punctuation matks).For example, in a line text, each word can be considered a token, and space separating the words can be considered delimiters.

#include<iostream>
using std::cout;
using std::endl;
#include<cstring>
int main()
{
char sentence[]="This is a sentence with 7 tokens";
char *tokenPtr;
cout<<"The string to be tokenized is:\n"<<sentence
    <<"\n\nThe tokens are:\n\n";
tokenPtr=strtok(sentence," ");
while(tokenPtr!=NULL)
{
cout<<tokenPtr<<'\n';
tokenPtr=strtok(NULL," ");
}
cout<<"\nAfter strtok, sentence="<<sentence<<endl;
return 0;
}

OUTPUT:

The string to be tokenized is:
This is a sentence with 7 tokens
The tokens are:
This
is 
a
sentence
with
7
tokens
After strtok, sentence=This

Determining String Lengths

Function strlen takes a string as an argument and returns the number of characters in the string the terminating null character is not included in the length.

#include<iostream>
using std::cout;
using std::endl;
#include<cstring>
int main()
{
char *string1="One";
char *string2="four";
chjar *string3="One One Four Four";
cout<<"The length of \""<<string1
    <<"\" is "<<strlen(string1)
    <<"\n The length of \""<<string2
    <<"\"is"<<strlen(string2)
    <<"\nThe length of\""<<string3
    <<"\"is"<<strlen(string3)<<endl;
return 0;
}

OUTPUT:

The length of "One" is 3
The length of "four" is 4
the length of "One One Four Four" is 17
Translate »