Site icon Learn C++

Learn to Use Strings in C++

In C programming language ASCII codes are used as in char arrays to store texts in ASCII mode. You can use char arrays in both C and C++, they are faster in operations and they have less memory usage. In s modern way, strings are useful for storing texts and they are defined in the string library. A string class contains a collection of characters surrounded by double quotes as we used in char arrays.

A string variable can be assigned as below,

[crayon-68dbd421ae299537408637/]

Here is the full C++ example that shows how to print out a string to screen,

[crayon-68dbd421ae2a2872296655/]

and the output will be,

[crayon-68dbd421ae2a3842885854/]

 

1. Reading and Modifying Characters of a string

strings are used like char arrays, you can reach each character by using [ ] brackets and the index number. See example below

[crayon-68dbd421ae2a7641481109/]

or you can use std in namespace so you don’t need to use std:: in each std commands as below,

[crayon-68dbd421ae2a8387986578/]

output will be second character as below,

[crayon-68dbd421ae2ac604046378/]

Note that index numbers in C and C++ starts with 0, and str[0] is ‘T’ character. We can modify character of a string as below,

[crayon-68dbd421ae2ad815759327/]

String Concatenation

strings are easy to operate with them in many ways, while we use strcat(), strcpy() functions in char arrays.

[crayon-68dbd421ae2ae768586325/]

strings are classes with many features, this is why they are preferred in modern C++. For example you can add another string by using its append() function.

[crayon-68dbd421ae2af117595225/]

this is same as

[crayon-68dbd421ae2b0914395938/]

Length of a string

Length of string, number of characters can be obtained by using it’s length() command as below,

[crayon-68dbd421ae2b3828113152/]

Size of a string

Size of string is size of string in the memory, if characters has 1 byte in compiler option this will equal to length, if characters has 2 bytes it will have double size of its length.

[crayon-68dbd421ae2b4702912662/]

Note that, in C++ Builder both string and String are used in same ways. In the last C++ Builder versions Strings are UnicodeString, supports globally and operations are explained before in Unicode Strings in C++ On Windows

Exit mobile version