首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C/C++ 字符串處理核心技術詳解:從 strcpy 到 memmove 的實戰指南

     編輯:VC 教學

章節概覽

本章透過思維導圖系統梳理字符串處理的核心知識點,涵蓋 C 風格字符串操作函數的實現原理、常見陷阱及最佳實踐。配合詳細的代碼範例,幫助開發者深入理解底層機制,避免緩衝區溢出等安全隱患。

字符串處理思維導圖 1

字符串處理思維導圖 2

點擊查看大圖

字符串處理思維導圖 3

核心函數實現剖析

Example 1: strcpy 手動實現

char *strcpy(char *target, const char *source) {
    char *t = target;
    // 複製 source 內容到 target
    while(*source) *target++ = *source++;
    // 為 target 添加空字符結尾
    *target = '\0';
    // 返回目標字符串起始指針
    return t;
}

關鍵點: 返回原始目標指針 t 而非移動後的 target,確保調用者能獲取字符串首地址。const 修飾 source 防止誤修改源數據。

Example 2: memmove 重疊內存安全複製

void *memmove(void *target, const void *source, size_t count)

與 memcpy 不同,memmove 能正確處理源與目標內存區域重疊的情況。雖然 source 為 const,但其指向的數組內容在重疊複製時可能被修改,這是實現時必須考慮的關鍵行為差異。

C 風格字符串操作實戰範例

Ex1: 基本操作演示

/* 
* Filename: 2-1.cpp
* Description: Fundamental Operations in C Type String
* Author: gnuhpc (https://blog.csdn.net/gnuhpc)
* Company: IBM CDL
*/
#include <iostream>
#include <cstring>

using namespace std;

int main(int argc, char *argv[]) {
    char strA[7] = "UP";
    char strB[5] = "DOWN";
    char strC[5] = "LEFT";
    char strD[6] = "RIGHT";

    /* 顯示初始字符串 */
    cout << "Here are the strings: " << endl;
    cout << "strA: " << strA << endl;
    cout << "strB: " << strB << endl;
    cout << "strC: " << strC << endl;
    cout << "strD: " << strD << "\n\n";

    // 顯示長度與大小差異
    cout << "Length of strA is " << strlen(strA) << endl;
    cout << "Size of strA is " << sizeof(strA) << endl;

    // 字符串拼接
    strcat(strA, strB);
    cout << "The result of Concatenate is strA: " << strA << endl;

    // 完全複製與部分複製
    strcpy(strB, strC);
    cout << "The result of Copy is: " << strB << endl;
    strncpy(strA, strD, 3);
    strA[3] = '\0'; // 手動添加結尾
    cout << "The result of partially Copy is strA: " << strA << endl;

    // 字符串比較
    if (!strcmp(strC, strB)) {
        cout << "strC is equal to strB!" << endl;
    }
    if (!strncmp(strD, strA, 3)) {
        cout << "strD is equal to strA partially!" << endl;
    }

    return 0;
}

實戰提示: strlen 返回邏輯長度(不含 \0),sizeof 返回數組佔用字節數;strncpy 不自動添加結尾符,需手動處理;比較函數返回 0 表示相等。

Ex2: 搜索與匹配操作

/* 
* Filename: 2-2.cpp
* Description: Search Operation in C type String
* Author: gnuhpc
*/
#include <iostream>
#include <cstring>
using namespace std;

int main(void) {
    const char *str = "Hello World, Hello C++";
    const char *target = "Hello";
    
    // strstr 查找子串首次出現位置
    char *pos = strstr(str, target);
    if (pos) cout << "Found at offset: " << (pos - str) << endl;

    // strchr 查找字符首次出現
    char *chPos = strchr(str, 'W');
    if (chPos) cout << "Char 'W' at: " << (chPos - str) << endl;

    // strcspn / strspn 字符集操作
    cout << "First non-alpha offset: " << strcspn(str, "0123456789") << endl;
    
    return 0;
}

[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 下一頁

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved