Functions for working with strings in C++

функции strlen (), strcat (), strcpy (), strcmp () в C++

After, as we are acquainted with strings and character arrays in C ++, look at the most common functions for working with them. The lesson will be fully built in practice. We will write their own programs-analogues for the treatment of strings and parallel to the use of standard library functions cstring (string.h – in older versions). So you're about to present itself, how they work. The standard library functions cstring include:

  • strlen() – calculates the length of the string (the number of characters excluding \0);
  • strcat() – it combines strings;
  • strcpy() – copies the symbols of one line to the other;
  • strcmp() – compares two strings together .

Это конечно не все функции, а только те, which is covered at the article.

strlen() (from the word length – length)

Our program, which will calculate the number of characters in a string:

For counting characters in a string of uncertain length (as it enters the user), we used the loop while – strings 13 – 17. It iterates through all the cells in the array (all the characters in a string) alternately, starting with zero. When at some step loop to meet Box ourStr [amountOfSymbol], that stores symbol \0, bust loop pause symbols and increase the counter amountOfSymbol.

So the code will look like, the replacement of our code section on the function strlen():

As you can see, this short code. It did not have to declare additional variables and use a loop. The output stream cout we passed into the function string – strlen(ourStr). It is suggested that the length of the string and back to the program number. As in the previous code-analog, symbol \0 not included in the total number of characters.

The result is the program in the first and second similar:

функция strlen () в C++

strcat() (from the word concatenation – connection)

Program, which at the end of one string, appends the second string. In other words – concatenates two strings.

According to comments in the code should be all clear. Below, we write a program to perform the same action, but using strcat(). In this feature, we will give two arguments (two strings) – strcat(someText1, someText2); . The function adds a string someText2 to line someText1. At the same symbol '' at the end someText1 It will overwrite the first character someText2. She also adds a final ''

Realization of unification of two strings, using standard function, took one string of code in a program – 14--s a string.


strcat c++, strcat_s c++

What should pay attention to the first and second code – size of the first character of the array should be sufficient for the second array of characters premises. If the size is insufficient – may occur abnormal program termination, since the string recording out of memory, which occupies the first array. For example:

In this case, a string constant “Learn C ++ c us!” It may not be written into the array someText1. As there is not enough space, for such operations.

If you are using a recent version of Microsoft Visual Studio development environment, you may experience the following error:: “error C4996: ‘strcat’: This function or variable may be unsafe. Consider using strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.” This is because, that has developed a new, more secure version of the function strcat – this is strcat_s. She cares about, to avoid buffer overflow (a character array, which produced record second string). Environment offers to use the new feature, instead of outdated. Read more about this can be on the msdn website. This error can appear, if you use the function strcpy, which will be discussed below.

strcpy() (from the word copy – copying)

Implement copying one string and its insertion in the place of another string.

Apply the standard function library cstring:

Try to compile and first, and a second program. You will see this result:

strcpy c++

strcmp() (from the word compare – comparison)

This function is designed to: she compares the two C-string character by character. If the strings are identical (and symbols and their number) – the function returns to the program number 0. If the first line is longer than a second – returns to the program number 1, and if less, then -1. The number of -1 back then, when the length of the strings is, but the characters of the strings do not match.

strcmp c++ program with strcmp():

strcmp c++

Share on social networks our articles with your friends, who also learn the basics of programming in C ++.

On our site already has the opportunity to subscribe, to receive notification of new articles. To subscribe – enter your e-mail below.

Newsletter of programming:

Functions for working with strings in C++
4.3 (86.67%) 12 votes

28 thoughts on “Functions for working with strings in C++

  1. Hello. Tell me please, why when combine two rows and the second character array specified array length, for example

    , then the second array is not combined with the first?

    1. It is not true.
      You have the result may simply be placed in someText1[].
      Increase its size – what greedy?
      For example: someText1[ 200 ]

  2. Explain, you are welcome, why in Example rows association with
    int count1 = 0; // for the cell where the index is stored ' 0’ first row
    while (someText1[count1] != 0)
    we are writing “someText1[count1] != 0” but not “someText1[count1] != ‘\0′”?
    We seem to be looking for an element of a character string end with ' 0'? What does the zero?
    Although I must say, I have a Koudblokse works with zero…

    1. Because the record ' 0’ once again, and means: bytes, numerical value recorded in which equal 0.
      Such records are equivalent.

  3. Dear author!
    To my mind, in the first comparison example rows directive omitted preprocessor #include

  4. Чета не могу понять
    char xsmibol[2] = {wParam, ‘\0’};
    вот так работает
    А вот так не работает:
    char xsmibol[2];
    xsmibol = {wParam, ‘\0’};

    Говорит 17 27 C:\Users\1\Documents\main1.cpp [Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
    17 12 C:\Users\1\Documents\main1.cpp [Error] assigning to an array from an initializer list
    37 14 C:\Users\1\Documents\main1.cpp [Error] expected primary-expression before ‘)’ token

    Что я делаю не так ?

Leave a Reply

Your email address will not be published. Required fields are marked *