Strcat_s(Newstring, Size, String + Strlen(String) - Back); Reads the Beginning Not the Bacl
After, equally we are acquainted with strings and character arrays in C ++, look at the well-nigh mutual 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). And then yous're about to present itself, how they piece of 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 ii strings together .
Это конечно не все функции, а только те, which is covered at the article.
strlen() (from the discussion length – length)
Our plan, which will calculate the number of characters in a string:
1 2 iii 4 5 6 7 8 9 ten 11 12 xiii 14 fifteen xvi 17 18 19 20 21 22 23 | #include <iostream> using namespace std ; int main ( ) { setlocale ( LC_ALL , "rus" ) ; char ourStr [ 128 ] = "" ; // для сохранения строки cout << "Введите текст латиницей (не больше 128 символов):\due north" ; cin . getline ( ourStr , 128 ) ; int amountOfSymbol = 0 ; // счетчик символов while ( ourStr [ amountOfSymbol ] != '\0' ) { amountOfSymbol ++ ; } cout << "Строка \"" << ourStr << "\" состоит из " << amountOfSymbol << " символов!\n\n" ; return 0 ; } |
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 lawmaking section on the part strlen() :
1 2 3 4 5 6 7 8 9 10 eleven 12 13 14 xv sixteen 17 18 | #include <iostream> #include <cstring> using namespace std ; int chief ( ) { setlocale ( LC_ALL , "rus" ) ; char ourStr [ 128 ] = "" ; // для сохранения строки cout << "Введите текст латиницей (не больше 128 символов):\n" ; cin . getline ( ourStr , 128 ) ; cout << "Строка \"" << ourStr << "\" состоит из " << strlen ( ourStr ) << " символов!\n\northward" ; render 0 ; } |
As you can run across, this short code. It did not have to declare additional variables and employ a loop. The output stream cout we passed into the office cord – 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 outcome is the plan in the first and 2d similar:
strcat() (from the word concatenation – connection)
Program, which at the end of one string, appends the second string. In other words – concatenates two strings.
i 2 3 4 five six 7 8 nine 10 11 12 13 fourteen 15 xvi 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std ; int primary ( ) { setlocale ( LC_ALL , "rus" ) ; char someText1 [ 64 ] = "Сайт purecodecpp.com!" ; char someText2 [ ] = "Учите С++ c нами!" ; cout << "Строка someText1- \"" << someText1 << "\" \due north" ; cout << "Строка someText2- \"" << someText2 << "\" \n\n" ; int count1 = 0 ; // для индекса ячейки где хранится '\0' первой строки while ( someText1 [ count1 ] != 0 ) { count1 ++ ; // ищем конец первой строки } int count2 = 0 ; // для прохода по символам второй строки начиная с 0-й ячейки while ( someText2 [ count2 ] != 0 ) { // дописываем вконец первой строки символы второй строки someText1 [ count1 ] = someText2 [ count2 ] ; count1 ++ ; count2 ++ ; } cout << "Строка someText1 после объединения с someText2 -\northward\"" << someText1 << "\" \n\n" ; render 0 ; } |
By the comments in the lawmaking should be clear. Below, we write a programme to perform the same deportment, only using strcat() . In this feature, we will give two arguments (2 strings) – strcat ( someText1 , someText2 ) ; . The office adds a string someText2to line someText1 . At the aforementioned symbol '' at the finish someText1 It will overwrite the starting time character someText2 . She too adds a final ''
1 2 iii iv 5 vi seven 8 nine 10 eleven 12 13 xiv fifteen 16 17 18 19 | #include <iostream> #include <cstring> using namespace std ; int main ( ) { setlocale ( LC_ALL , "rus" ) ; char someText1 [ 64 ] = "Сайт purecodecpp.com!" ; char someText2 [ ] = "Учите С++ c нами!" ; cout << "Строка someText1 - \"" << someText1 << "\" \north" ; cout << "Строка someText2 - \"" << someText2 << "\" \n\n" ; strcat ( someText1 , someText2 ) ; // передаём someText2 в функцию cout << "Строка someText1 после объединения с someText2 -\northward\"" << someText1 << "\" \n\due north" ; return 0 ; } |
Realization of unification of ii strings, using standard function, took 1 string of code in a programme – 14--s a string.
Result:
What should pay attending to the first and second code– size of the kickoff character of the array should be sufficient for the 2d array of characters premises. If the size is insufficient – may occur aberrant program termination, since the string recording out of memory, which occupies the start assortment. For example:
char someText1 [ 22 ] = "Сайт purecodecpp.com!" ; strcat ( someText1 , "Учите С++ c нами!" ) ; |
In this case, a string constant"Learn C ++ c us!" It may not be written into the array someText1 . As at that place is not plenty infinite, for such operations.
If you are using a contempo version of Microsoft Visual Studio evolution surround, you may feel the post-obit error:: "error C4996: ‘strcat': This function or variable may exist 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 well-nigh, to avert buffer overflow (a graphic symbol array, which produced record 2d string). Environment offers to utilize the new feature, instead of outdated. Read more about this can be on the msdn website. This mistake can announced, if you use the office strcpy , which volition exist discussed below.
strcpy() (from the word re-create – copying)
Implement copying one string and its insertion in the identify of another string.
1 2 three 4 5 6 7 8 9 10 11 12 thirteen 14 xv sixteen 17 18 nineteen 20 21 22 23 24 25 26 27 28 29 xxx | #include <iostream> using namespace std ; int main ( ) { setlocale ( LC_ALL , "rus" ) ; char someText1 [ 64 ] = "Сaйт purecodecpp.com!" ; char someText2 [ ] = "Основы С++" ; cout << "Строка someText1 - \"" << someText1 << "\" \n" ; cout << "Строка someText2 - \"" << someText2 << "\" \n\n" ; int count = 0 ; while ( true ) // запускаем бесконечный цикл { someText1 [ count ] = someText2 [ count ] ; // копируем посимвольно if ( someText2 [ count ] == '\0' ) // если нашли \0 у второй строки { break ; // прерываем цикл } count ++ ; } cout << "Строка someText1 после копирования someText2 -\due north\"" << someText1 << "\" \n\northward" ; return 0 ; } |
Apply the standard function library cstring:
1 2 3 4 5 6 7 viii 9 10 11 12 thirteen 14 15 xvi 17 18 19 twenty | #include <iostream> #include <cstring> using namespace std ; int master ( ) { setlocale ( LC_ALL , "rus" ) ; char someText1 [ 64 ] = "Сaйт purecodecpp.com!" ; char someText2 [ ] = "Основы С++" ; cout << "Строка someText1 - \"" << someText1 << "\" \n" ; cout << "Строка someText2 - \"" << someText2 << "\" \n\northward" ; strcpy ( someText1 , someText2 ) ; // передаём someText1 и someText2 в функцию cout << "Строка someText1 после копирования someText2 -\n\"" << someText1 << "\" \northward\north" ; return 0 ; } |
Attempt to compile and offset, and a second program. You will see this event:
strcmp() (from the word compare – comparison)
This role is designed to: she compares the two C-string character by grapheme. If the strings are identical (and symbols and their number) – the function returns to the program number 0. If the kickoff line is longer than a second – returns to the program number 1, and if less, and so -1. The number of -1 back and then, when the length of the strings is, simply the characters of the strings exercise not lucifer.
1 ii 3 4 5 half dozen 7 8 ix ten 11 12 13 14 xv sixteen 17 18 xix xx 21 22 23 24 25 26 27 28 29 xxx 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | #include <iostream> using namespace std ; int main ( ) { setlocale ( LC_ALL , "rus" ) ; char someText1 [ ] = "Сaйт purecodecpp.com!" ; char someText2 [ ] = "Сaйт purecodecpp.com/" ; cout << "Строка someText1 - \"" << someText1 << "\" \due north" ; cout << "Строка someText2 - \"" << someText2 << "\" \north\n" ; int compare = 0 ; // для сравнения длины строк int count = 0 ; while ( true ) { if ( strlen ( someText1 ) < strlen ( someText2 ) ) { cout << "Строки НЕ равны: " << -- compare << endl ; break ; } else if ( strlen ( someText1 ) > strlen ( someText2 ) ) { cout << "Строки НЕ равны: " << ++ compare << endl ; interruption ; } else // если по количеству символов строки равны { if ( someText1 [ count ] == someText2 [ count ] ) // сравниваем посимвольно включая \0 { count ++ ; if ( someText1 [ count ] == '\0' && someText2 [ count ] == '\0' ) { cout << "Строки равны: " << compare << endl ; break ; } } else // если все же где-то встретится отличный символ { cout << "Строки НЕ равны: " << -- compare << endl ; intermission ; } } } render 0 ; } |
program with strcmp() :
i two 3 four v 6 7 8 9 10 11 12 thirteen 14 15 16 17 18 | #include <iostream> #include <cstring> using namespace std ; int master ( ) { setlocale ( LC_ALL , "rus" ) ; char someText1 [ ] = "Сaйт purecodecpp.com!" ; char someText2 [ ] = "Сaйт purecodecpp.com/" ; cout << "Строка someText1 - \"" << someText1 << "\" \due north" ; cout << "Строка someText2 - \"" << someText2 << "\" \north\n" ; cout << strcmp ( someText1 , someText2 ) << endl << endl ; return 0 ; } |
Share on social networks our articles with your friends, who also learn the basics of programming in C ++.
Source: https://purecodecpp.com/en/archives/920
0 Response to "Strcat_s(Newstring, Size, String + Strlen(String) - Back); Reads the Beginning Not the Bacl"
Publicar un comentario