Strcat function in cpp

C++ String Function: strcpy(), strcat(), strlen(), strcmp() Example

A string is a sequence of characters. A C++ string is an object of the std::string class. The characters are stored sequences of bytes with access to a single character byte allowed.

C++ strings allocate memory dynamically. More memory can be allocated to the string during run time if needed. Since there is no memory pre-allocation, no wastage of memory. We can perform various operations on strings, including comparisons, concatenation, conversion, etc.

Declaring Strings

C++ supports two types of string declarations:

C-Style Character String

This type of string declaration was introduced in C programming language. C++ continues to support it. It’s simply a one-dimensional array of characters terminated with a null character (\0). A null-terminated string has characters that make up the string then followed by a null.

Consider the string declaration given below:

The above declaration creates a string that forms the word John. The word has 4 characters, but the string has a size of 5. The extra space allows for holding of the null character.

Using the array initialization rule, we can write the above statement as follows:

Note that you don’t have to place the null character at the end of the string constant. The C++ compiler will automatically place the ‘\0’ at the string’s end when initializing the array.

Читайте также:  Css div horizontal centered

std::string

The standard C++ library provides the string class which supports various string operations. It is written as std::string.

To use this class, we must first include it into our workspace using the #include preprocessor as shown below:

Next, we can declare our string using the string keyword. For example:

The above statement will create a string named name to hold the value John.

Accessing string Values

In C++, we can access the string values using the string name. For example:

#include using namespace std; int main() < char name[5] = < 'J', 'o', 'h', 'n', '\0' >; cout

Accessing string Values

Here is a screenshot of the code:

Accessing string Values

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The < marks start of body of the main() function.
  4. Declaring a string of characters and giving it the name name. The string will store the value John. The extra space will store the null character.
  5. Printing some text on the console.
  6. Printing the value of the string named name on the console.
  7. The main() function should return an value if the program runs fine.
  8. End of the body of the main() function.

Here is another example using the C++ standard string class:

#include #include using namespace std; int main()

Accessing string Values

Here is a screenshot of the code:

Accessing string Values

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the standard string class in our code.
  3. Including the std namespace so as to use its classes and functions without calling it.
  4. Calling the main() function inside which the logic of the program should be added. The < marks start of body of the main() function.
  5. Declaring a string and giving it the name name. The string will store the value Guru99.
  6. Printing the value of the string name alongside some text on the console.
  7. The main() function should return an value if the program runs fine.
  8. End of the body of the main() function.

String Functions in C++

You will often want to manipulate strings. C++ provides a wide range of functions that you can use for this. These functions are defined in the CString class, hence, we have to include it in our code in order to use the functions. Let us discuss some:

strcpy()

This is the string copy function. It copies one string into another string.

The two parameters to the function, string1 and string2, are strings. The function will copy the string string1 into the string 1.

strcat()

This is the string concatenate function. It concatenates strings.

The two parameters to the function, string1 and string2 are the strings to be concatenated. The above function will concatenate the string string2 to the end of the string string1.

strlen()

This is the string length function. It returns the length of the string passed to it as the argument.

The parameter string1 is the name of the string whose length is to be determined. The above function will return the length of the string string1.

strcmp()

This is the string compare function. It is used for string comparison.

The above function will return 0 if strings string1 and string2 are similar, less than 0 if string1string2.

Example:

The following example demonstrates how to use the above string functions:

#include #include using namespace std; int main()

String Functions in C++

Here is a screenshot of the code:

String Functions in C++

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the standard CString class in our code.
  3. Including the std namespace so as to use its classes and functions without calling it.
  4. Calling the main() function inside which the logic of the program should be added. The < marks start of body of the main() function.
  5. Declaring a string of 10 characters and giving it the name name1. The string will store the value Guru99.
  6. Declaring a string of 10 characters and giving it the name name2. The string will store the value John.
  7. Declaring a string of 10 characters and giving it the name name3.
  8. Declaring an integer variable named len.
  9. Copying the string name1 into the string name3.
  10. Printing the value of the string name1 alongside some text on the console. It should print Guru99.
  11. Concatenating the strings name2 to the end of string name1. The value of name1 is now Guru99John.
  12. Printing the value of the string name1 alongside some text on the console. It should print Guru99John
  13. Determining the length of the string named name1 and assigning the value of length to variable len.
  14. Printing the value of len variable alongside some other text on the console.
  15. The main() function should return an value if the program runs fine.
  16. End of the body of the main() function.

Summary

  • A string is a sequence of characters.
  • Strings belong to the standard string class in C++.
  • We can declare strings using the C-style character string or standard string class.
  • The strcpy() function copies one string into another.
  • The strcat() function concatenates two functions.
  • The strlen() function returns the length of a function.
  • The strcmp() function compares two strings.

Источник

strcat , wcscat , _mbscat

Appends a string. More secure versions of these functions are available; see strcat_s , wcscat_s , _mbscat_s .

_mbscat_s cannot be used in applications that execute in the Windows Runtime. For more information, see CRT functions not supported in Universal Windows Platform apps.

Syntax

char *strcat( char *strDestination, const char *strSource ); wchar_t *wcscat( wchar_t *strDestination, const wchar_t *strSource ); unsigned char *_mbscat( unsigned char *strDestination, const unsigned char *strSource ); template char *strcat( char (&strDestination)[size], const char *strSource ); // C++ only template wchar_t *wcscat( wchar_t (&strDestination)[size], const wchar_t *strSource ); // C++ only template unsigned char *_mbscat( unsigned char (&strDestination)[size], const unsigned char *strSource ); // C++ only 

Parameters

strDestination
Null-terminated destination string.

strSource
Null-terminated source string.

Return value

Each of these functions returns the destination string ( strDestination ). No return value is reserved to indicate an error.

Remarks

The strcat function appends strSource to strDestination and terminates the resulting string with a null character. The initial character of strSource overwrites the terminating null character of strDestination . The behavior of strcat is undefined if the source and destination strings overlap.

Because strcat does not check for sufficient space in strDestination before appending strSource , it is a potential cause of buffer overruns. Consider using strncat instead.

wcscat and _mbscat are wide-character and multibyte-character versions of strcat . The arguments and return value of wcscat are wide-character strings. The arguments and return value of _mbscat are multibyte-character strings. These three functions behave identically otherwise.

In C++, these functions have template overloads that invoke the newer, secure counterparts of these functions. For more information, see Secure template overloads.

Generic-text routine mappings

TCHAR.H routine _UNICODE and _MBCS not defined _MBCS defined _UNICODE defined
_tcscat strcat _mbscat wcscat

Requirements

Routine Required header
strcat
wcscat or
_mbscat

For more compatibility information, see Compatibility.

Example

Источник

strcat , wcscat , _mbscat

Дополняет строку. Доступны более безопасные версии этих функций; См. , strcat_s wcscat_s , _mbscat_s .

_mbscat_s не может использоваться в приложениях, запускаемых в среде выполнения Windows. Дополнительные сведения: Функции CRT, которые не поддерживаются в приложениях универсальной платформы Windows.

Синтаксис

char *strcat( char *strDestination, const char *strSource ); wchar_t *wcscat( wchar_t *strDestination, const wchar_t *strSource ); unsigned char *_mbscat( unsigned char *strDestination, const unsigned char *strSource ); template char *strcat( char (&strDestination)[size], const char *strSource ); // C++ only template wchar_t *wcscat( wchar_t (&strDestination)[size], const wchar_t *strSource ); // C++ only template unsigned char *_mbscat( unsigned char (&strDestination)[size], const unsigned char *strSource ); // C++ only 

Параметры

strDestination
Строка назначения, завершающаяся нуль-символом.

strSource
Исходная строка, завершающаяся символом NULL.

Возвращаемое значение

Каждая из этих функций возвращает строку назначения ( strDestination ). Нет зарезервированных возвращаемых значений для указания ошибки.

Комментарии

Функция strcat добавляет strSource в strDestination и завершает результирующую строку символом NULL. Начальный символ строки strSource переопределяет завершающий нуль-символ строки strDestination . При перекрытии исходного и конечного буферов поведение strcat не определено.

strcat не проверяет, достаточно ли места в строке strDestination , перед добавлением strSource , в связи с чем может возникнуть ошибка переполнения буфера. Вместо него рекомендуется использовать класс strncat .

Функции wcscat и _mbscat are wide-character и multibyte-character versions of strcat для расширенных и многобайтовых символов. Аргументы и возвращаемое значение являются wcscat строками расширенных символов. Аргументы и возвращаемое значение являются _mbscat многобайтовыми строками символов. В остальном эти три функции ведут себя идентично.

В C++ эти функции имеют шаблонные перегрузки, которые вызывают более новые и безопасные аналоги этих функций. Дополнительные сведения см. в разделе Безопасные перегрузки шаблонов.

Сопоставления подпрограмм с универсальным текстом

TCHAR.H Обычной _UNICODE и _MBCS не определены _MBCS Определенные _UNICODE Определенные
_tcscat strcat _mbscat wcscat

Требования

Подпрограмма Обязательный заголовок
strcat
wcscat или
_mbscat

Дополнительные сведения о совместимости см. в разделе Compatibility.

Источник

Оцените статью