Functions for working with strings in C++

Rate this article




функции 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.

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 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:

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

  1. There milyard pieces, you may have missed, but we describe in great detail the obvious…

    >> Program, which at the end of one string, appends the second string. In other words - it combines two lines.

    So, and in other words – various shots, but the essence is not clear.
    I have 2 char * string for each allocated 256 bytes.
    The first recorded “hello”, second “world”.
    I unite them. How many bytes I needed? 512 or 10?

    Answer and go further in the text :).

    1. Vladimir, pointers topic in this article does not rise. If we talk about character arrays (Si-strokah) size 256 bytes each, after string concatenation “hello” and ” world”, row in which the characters are finished writing world, will take 256 bytes, as well as prior to the merger.

      strWorld string takes strHello cell line, following the characters hello (strWorld first character of the string “zatret” \0 after the symbol 'o’ strHello line).

      Working with pointers to strings, of course, better perevydelyat amount of memory required to store strings of characters, and not occupy too much space. It will turn, what is necessary 12 byte for “hello world”. All in order – and we come to this :)

      P.S. comments,code and an explanation is not for you, and for beginners, which will read something about what we are talking

      1. The question is really very interesting! I have never had to think about it. At first sight, in this record is not strange. But it does not work well! :) Error states “The buffer is too small”. A friend of mine (Vitali) I said so to the question: “written documentation, what “if the function objects overlap, its behavior is not defined.” the programmer who writes so sucked into the void )) ” Well, even so continued: “It goes up one character. The function searches \0 the first line, finds, character by character and starts to glue the second row. BUT! it will glue until it finds \0 which no longer exists!
        Vova, we are grateful, If you, too, will answer us on this issue.

  2. Well, right comrade said, The first line copies the characters from its beginning to its end, therefore grows infinitely.

    The mane is written:
    Lines can not overlap, and dest must have enough space to hold the result.

    In reality, there is a buffer overflow, but purely by chance it might work (the error does not come out), but the program is modified somehow unpredictable.

    Dokapalis I to, that the description of this function takes mana lines 6. Just, clear all at once (and about large enough buffers, and about the intersection of the lines). You write a hundred times the same thing with different words, I do not know why xD.

    >> P.S. comments,code and an explanation is not for you, and for beginners, which will read something about what we are talking.

    You're writing an article about coding conventions. It seems like some of them indicates the optimal number of comments in the code. Nobody writes to each line.

    Å ê in non indeksiruetsâ Poiskovik (or I'm wrong?), so just more profitable to put a description to the code after the code, not inside.

    You are writing, “functions for working with strings in C ++”, actually they once were in , but in C ++ there , and old (“sishnye”) string passed in (here there and described these sorts strcat, … ). That is. I read the title and expect to read about std::string, and here… (They deceived me xD).

    1. so no comments in the code for each line )) there are only a couple of pieces. P.S. It was written to, that you do not think if I told you all this explain. You know what – It's clear ))
      With regard to the title. By name certainly can nitpick… Only if the article was about the string, it also will not name “functions for working with strings in C ++”. rather – Methods for working with strings Class string objects.
      How would you call this article? Maybe the truth is better to rename.

  3. But I read an article on…

    About strcpy you brought something analogue type, i.e.. tried gash strcpy own hands, I understand correctly?

      1. Not exactly xD.

        The mane (standard seems too) It says that the lines do not overlap. In gcc it seems to work out fine overlapping lines, but this standard may be undefined behavior, and means in another compiler (another version of the same compiler) it may break.

        I think, that on this topic better describe typical errors (с strcpy – This buffer overflow) and ways to combat.

        I'd thought about crafts melkosofta, type strcpy_s. If you are writing code in visual studio, then you will hear and stopudovo warning window that, strcpy that must be replaced by a secure version – strcpy_s. That's about this thing you can write IMHO.
        Look here

      2. Well about strcpy_s and strcat_s – This was my question for you )) It turns out Now, that the question asked itself.

        Interesting you have a way of communicating:
        – just.
        – Not exactly.

        + My questions are the same, and I ask…

        Vova. I propose to communicate well, if we respect each other )

  4. but a whole article became Godnev, code formatted least uniformly :). More fun is not enough examples, whether…

    Write more :)

      1. >> Vova. I propose to communicate well, if we respect each other )

        “On you” whether? )

        About the more correct name entries do not know anything. I'm not a fan of mikrostatey, I would write under this name, and about C-string, a string of. I have come up with some example, which would have brought a bunch of string functions, and by the functions themselves have written a very short (otnostrochnыe) comments, I would have brought them to the table. Posted to about buffer overflow – just do a common mistake when working with strings, safe-functions from Microsoft and another example of the type… “given an array of strings, it is necessary to merge it into one big string” – there would be stopped on the evaluation of the asymptotic complexity – Example gorgeous and assessment of complexity does not lie on the surface.

        I do not so much ask questions, many suggest topics for the following articles (theses or to finished current).

      2. Anyway – thank you for the constructive criticism and suggestions! It is interesting to communicate with you

  5. About the example of the merger will explain the array of strings.
    is an artifact from strcat, here you are right already written, that before you begin to merge, it replaces the symbol . But to his zanmenit, it is necessary to find. But how to find it, If the string size is not known? – iterate sequentially all line items.

    If you merge 2 strings – the first length N, second – M, it will be executed N + M operations, tk. first N operations to find , M operations and then to record the contents of the second row in the first.

    Although, many programmers, do not look into the documentation of operations expected M, tk. forget about the search.

    Respectively, if we have an array of K lines, and so will, that the first line is too long, and the rest are very short, the complexity of the algorithm is not very small (although, because we add a short string to a long), and close to K * only, где Only – the sum of the lengths of all strings. In short, instead of the linear quadratic complexity.

    But in std::string all very different, although the complexity will remain the same (about, because there are things such as memcpy, and the vector can grow in spurts) despite, that the lines of known size. think why, MB draw a new article.

    1. A couple of lines in the protection of the author!
      Vladimir, appeal to you “About the more correct name entries do not know anything” – there is nothing to find fault with the invented name, and it turns out – I do not like, but I do not know how best to… “I would write…”, “I came up to…”, ” brought to…” and t. д. and so on. But I do not write, did not invent, not brought… (If I'm too categorical and deeply wrong – share, Be kind to link to your article on the same topic). And someone wrote, invented, did. And you are now sidiete “all so smart” and criticize. I would have made a lot of good…. While someone picks and makes! I like the article and is very popular and understandable examples. The presentation much clearer than my current teacher at the university in C ++ (Another compliment to the author). Many thanks to the mastered this site rather than studies and abstracts (but sadly). Author, Thank you for your work! Do not stop there, Your efforts benefit people!

  6. the first example of comparison about 2 lines I have not compiled without
    #Example include but it is not specified.

    1. The examples in the literature (and much more complex, than shown) frequently required #include not specified – considered, you will enter their own in the required quantity.

      Specifically, the, which required #include, may vary depending on the operating system and compiler … but not all (fortunately) MS VisualStudio like you.

    1. if( 0 == strcmp( str1, str2 ) ) /* string matching * /
      else /* do not match */

      Other return values (0) means leksograficheskoe ordering strings str1 and str2 … but it needs to represent, what leksografichesky order.

Leave a Reply

Place code in tags: <pre class="lang:c++ decode:true ">YOUR CODE</pre>