當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ strcat()用法及代碼示例

在 C/C++ 中,strcat() 是用於字符串處理的預定義函數,位於字符串庫(C 中的 string.h 和 C++ 中的 cstring)下。

此函數將 src 指向的字符串附加到 dest 指向的字符串的末尾。它將在目標字符串中附加源字符串的副本。加上一個終止的 Null 字符。字符串(src)的初始字符會覆蓋字符串(dest)末尾的 Null-character。

如果出現以下情況,則行為未定義:

  • 目標數組對於 src 和 dest 的內容以及終止的空字符都不夠大
  • 如果字符串重疊。
  • 如果 dest 或 src 不是指向以 null 結尾的字節字符串的指針。

用法:



char *strcat(char *dest, const char *src)

參數:該方法接受以下參數:

  • dest:這是一個指向目標數組的指針,它應該包含一個 C 字符串,並且應該足夠大以包含連接的結果字符串。
  • src:這是要附加的字符串。這不應與目的地重疊。

返回值:strcat()函數返回目標字符串的指針dest。

應用:給定C++中的兩個字符串src和dest,我們需要將src指向的字符串追加到dest指向的字符串的末尾。

例子:

Input:src = "ForGeeks"
       dest = "Geeks"
Output:"GeeksForGeeks"

Input:src = "World"
       dest = "Hello "
Output:"Hello World"

下麵是實現上述方法的 C 程序:

C


// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>
  
// Driver code
int main(int argc,
         const char* argv[])
{
    // Define a temporary variable
    char example[100];
  
    // Copy the first string into
    // the variable
    strcpy(example, "Geeks");
  
    // Concatenate this string
    // to the end of the first one
    strcat(example, "ForGeeks");
  
    // Display the concatenated strings
    printf("%s\n", example);
  
    return 0;
}
輸出:
GeeksForGeeks

注意:
目標字符串應該足夠大以容納最終字符串。

相關用法


注:本文由純淨天空篩選整理自dhanshreekulkarni21大神的英文原創作品 strcat() function in C/C++ with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。