首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 字符串順序串操作:數組實現插入、刪除、替換、查找完整代碼修正

     編輯:程式設計疑難解答

核心錯誤

多處 `if (s[0] = '0')` **賦值代替比較**,導致條件永真/假,邏輯錯誤。應為 `if (s[0] == '0')` 或 `if (s[0] == '\0')` 判空。

修正關鍵函數


// 輸出串
void output(char *s) {
    if (s[0] == '\0')  // 判空
        cout << "該串為空串,請重新輸入!" << endl;
    else
        cout << s << endl;
}

// 計算長度
int length(char s[]) {
    int i = 0;
    if (s[0] == '\0') {  // 修正比較
        cout << "該串為空串,請重新輸入!" << endl;
        return 0;
    }
    while (s[i] != '\0') i++;
    cout << "該串長為:" << i << endl;
    return i;
}

其他邏輯修正要點

  • `Insert`、`contact` 中 `length(q)+length(t)>255` 檢查應在移動數據**前**進行。
  • `replace` 循環 `q[i-1]=t[k]` 索引錯誤,應 `q[i+k]=t[k]`。
  • `index` (查找子串) 邏輯有誤,建議用標準 `strstr` 或 KMP 算法。
  • 菜單 `switch` 缺少 `case 'a':` 等標簽,直接 `output(s);` 導致所有分支落入 default。

建議:使用標準庫


#include 
#include 

string s, t;
// 插入: s.insert(pos, t);
// 刪除: s.erase(pos, len);
// 替換: s.replace(pos, len, t);
// 查找: size_t pos = s.find(t);
// 子串: string sub = s.substr(pos, len);
// 連接: s += t;

**教學階段理解數組實現原理即可,實際開發請直接用 `std::string`**,安全、高效、功能全。

小建議

菜單 `switch` 每個 `case` 結束加 `system("cls")` (Windows) 或 `system("clear")` (Linux/Mac) 清屏,體驗更好。

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