You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++字符串管理:动态字符串数组的长度获取、修改与报错处理

你代码中首先存在一个严重的越界问题:string* word = new string[0];申请的是长度为0的动态数组,此时访问word[0]属于未定义行为,会直接触发崩溃或不可预期的结果,需要先修改为对应需要的数组长度,比如仅需要存储1个字符串就改为new string[1];。

获取string字符串的长度

std::string类自带size()和length()方法,直接调用即可,不需要依赖C标准库的strlen函数:

int str_len = word[0].size();

处理字符串并自动调整大小

std::string内部自动管理内存,不需要你手动调用接口调整大小,处理完成后直接赋值即可,会自动适配新的字符串长度。
你需要的过滤逻辑是:把字符串中的_.替换为空格,删除单独的.字符,遍历实现逻辑如下:

string tmp;
int i = 0;
int len = word[0].size();
while(i < len) {
    // 匹配_.组合,替换为空格
    if(i+1 < len && word[0][i] == '_' && word[0][i+1] == '.') {
        tmp += ' ';
        i += 2;
        continue;
    }
    // 跳过单独的.
    if(word[0][i] == '.') {
        i++;
        continue;
    }
    // 其余字符直接保留
    tmp += word[0][i];
    i++;
}
// 直接赋值,string自动调整内存大小
word[0] = tmp;

类型不匹配报错的解决方法

strcpy、strlen等都是C标准库的字符串处理函数,仅接受char*类型的C风格字符串参数,你传入std::string类对象自然会触发类型转换报错。
如果你一定要使用这些C函数,可以调用std::string的c_str()方法获取只读的C风格字符串指针:

// 仅可用于读取,不可修改指针指向的内容
int c_len = strlen(word[0].c_str());

但不建议混用C和C++的字符串处理逻辑,std::string自带了足够的字符串操作方法,完全可以满足编辑需求。

完整可运行代码(不使用vector)

#include <iostream>
#include <string>

using namespace std;

int main()
{
    // 申请长度为1的动态string数组,符合不使用vector的要求
    string* word = new string[1];
    word[0] = "apple_.Tree.";

    cout << "原字符串:" << word[0] << endl;
    cout << "原长度:" << word[0].size() << endl;

    // 字符串处理逻辑
    string processed;
    int i = 0;
    int n = word[0].size();
    while (i < n) {
        if (i + 1 < n && word[0][i] == '_' && word[0][i+1] == '.') {
            processed += ' ';
            i += 2;
        } else if (word[0][i] == '.') {
            i += 1;
        } else {
            processed += word[0][i];
            i += 1;
        }
    }
    word[0] = processed;

    cout << "处理后字符串:" << word[0] << endl;
    cout << "处理后长度:" << word[0].size() << endl;

    // 释放动态数组内存,避免泄漏
    delete[] word;
    return 0;
}

运行输出:

原字符串:apple_.Tree.
原长度:12
处理后字符串:apple Tree
处理后长度:10

内容的提问来源于stack exchange,提问作者Jesepy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 23:54:05