The basics of programming in c++ for beginners

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 BoxourStr [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 functionstrlen():

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.

By the comments in the code should be clear. Below, we write a program to perform the same actions, but using strcat(). In this feature, we will give two arguments (two strings) – strcat(someText1, someText2); . The function adds a stringsomeText2 to linesomeText1. At the same symbol ''  at the end someText1It will overwrite the first charactersomeText2. 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.

Result:

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 arraysomeText1. 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 functionstrcat  – this isstrcat_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 functionstrcpy, 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 librarycstring:

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 withstrcmp():

strcmp c++

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

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

  1. while (true) // запускаем бесконечный цикл
    {
    someText1[count] = someText2[count]; // copy one character
    if (someText2[count] == ‘’) // если нашли \0 у второй строки
    {
    break; // прерываем цикл
    }
    count ;
    }
    I do not understand what happened to the rest of the line “Сaйт purecodecpp.com!” ,
    if the idea should happen: Basics With ++ pp.com.
    We copy one character fewer rows in a large, so why residue someText1 removed?

    1. because, that we copy in no less great, and the second in the first. And when suitable ' 0’ in the second row it is also overwritten in the first array. Further, when the first array will be read, then this will show zero and the end of the line, and it does not matter, there was written for him. This will be the end of the line.

  2. #include
    #include
    using namespace std;

    int main()
    {
    setlocale(LC_ALL, “rus”);

    char string_Array_1[] = “Vasya, what are you, weary?”;
    char string_Array_2[] = “Vasya, what are you, weary!”;

    cout << "Первая строка – \"" << string_Array_1 << "\"\n";
    cout << "Вторая строка – \"" << string_Array_2 << "\"\n";
    cout << "=====================================================\n\n";
    cout << "Если строки идентичны и по символам и по количеству, then: 0\n";
    cout << "Если первая строка длиннее второй, then: +1\n";
    cout << "Если первая строка короче второй, then: -1\n";
    cout << "Если длина строк равна, but the characters do not match, then: -1\n";
    cout << "=====================================================\n\n";
    cout << "В приведенном случае получился ответ: " << strcmp(string_Array_1 , string_Array_2);
    cout << endl << endl;

    return 0;
    }

    turn out:

    First line – "Вася, what are you, weary?"
    The second line – "Вася, what are you, weary!"
    ==========================================================

    If the strings are identical and the symbols and the number of, then: 0
    If the first line is longer than a second, then: +1
    If the first line is shorter than a second, then: -1
    If the row length is, but the characters do not match, then: -1
    ===========================================================

    In this case, I get answers: 1

    I can not understand, why 1, If at the end of rows different characters: ? and !

    1. Interesting bug in the code.
      I copied, made two similar text “Vasya, what are you, weary!” в char string_Array_1[] и char string_Array_2[] and checked:
      1. While the strings are the same all GOOD!!!
      2. If the first line to make it get longer ” -1 ” (inverted).
      3. If the first line to make it get shorter ” 1 ” (inverted).
      more interesting.
      4. If the first line in the word ” weary ” letter ” in ” change to ” t ” I get ” -1 ”
      5. If the first line in the word ” weary ” letter ” in ” change to ” f ” I get ” 1 ”
      6. If the second line in the word ” weary ” letter ” in ” change to ” t ” I get ” 1 ”
      7. If the second line in the word ” weary ” letter ” in ” change to ” t ” I get ” -1 ”
      Word ” weary ” I took as an example. letter ” in ” I changed to the previous and next in the alphabet. It works with any replacement of letters ( ” and ” and ” I ” I could not change).

      1. This is not a bug (as I thought). This is due to ASCII encoding. ASCII character set can be very zaguglit. So it turns out that “in” More on this encoding “t” and less “f”

    1. The more characters in ASCII code table of the “longer”.
      “B” longer “A”, and “D” longer “B”.
      Punctuation is also a concern.
      IN “!” code 33, in “?” code 63, so ? > !

      1. Yes, little understood, I understood (I guessed) that here there is a peg to the ASCII

      2. I assume that the function simply adds up all the numbers and compares the sum 1 rows with sum 2.
        Replaced lines
        “AaaaaAaaaaAaaaaAaaaaaAaaaaAaaaaa”
        “ZzzzzZzzzzZzzzzZzzzzZzzzzZzzz”
        the answer was -1
        though 1 string is longer. Well, I have the right to make mistakes :))

  3. >>Yes, little understood, I understood (I guessed) that here there is a peg to >>ASCII encoding
    No “binding” to the encoding there, compare numbers, CPU does not exist or no character encodings, but only a number, and then in the binary system!

  4. good afternoon. I have a question. How can I write text entered from the console into an array, without announcing it in advance. For example, if we do not know the size of the string, entered by user, but we don’t want to declare an empty array in advance
    with random size (suddenly we will indicate a smaller size, than the one you need.).It turns out that the user enters a string, presses input and further, an array should be created suitable for storing this character set.

      1. Can you help? How to write text to a matrix row by row and then rewrite it from the center in a spiral?

Leave a Reply to Alexashka Cancel reply

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