c++ - 从字符数组中提取字符串

标签 c++ input substring character

我试过 memcpy/strncpy/std::copy 但它们似乎都不起作用导致程序崩溃。

这是我需要做的:

例如,我正在尝试解析来自用户输入的争论。 “消息-添加 0xAE”

我需要将 0xAE 部分提取为整数,这是一些伪代码 _input 将保存完整的字符串“message -add 0xAE”

if(strstr(_input,"message -add 0x")){
    char* _temp;
    std::copy(strlen("message -add 0x"),strlen("message -add 0x")+(strlen(_input)-strlen("message -add  0x")),_temp);
    /* or */
    memcpy(_temp,_input+strlen("message -add 0x"),strlen(_input)-strlen("message -add 0x"));
    int _value = (int)_temp;
    CLog->out("\n\n %d",_value);
}

编辑:谢谢艾伦!

if(strstr(_input,"message -add 0x")){
            char* _temp = new char[strlen(_input)-strlen("message -add 0x")];
            memcpy(_temp,_input+strlen("message -add 0x"),strlen(_input)-strlen("message -add 0x"));
            int _value = atoi(_temp);
            CLog->out("\n\n %d",_value);
}

最佳答案

您在寻找:

int value = 0;
char c;
for(int i = strlen("message -add 0x"); c = *(_input + i); i++) {
    value <<= 4;
    if(c > '0' && c <= '9') {
        // A digit
        value += c - '0';
    } else if(c >= 'A' && c < 'G') {
        // Hexadecimal
        value += 10 + c - 'A';
    }
}

?

关于c++ - 从字符数组中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699097/

相关文章:

c++ - 稀疏容器和迭代器

c++ - 来自数组的 Memcpy 只能正确工作 1/20 个实例?

c++ - 从到严格增加值的元素的映射的内存使用情况

angular - 如何在 Angular 6 项目中使用 ng2-currency-mask

javascript - 如何在 javascript 中获取具有 3 个选项的输入单选按钮的值?

java - 在 Java 中检查字符串值

c++ - 仅从 boost 中获取必要的 header

excel - VBA 如何强制用户使用 Excel 的内置范围选择来选择范围?

python - 在python中的列表中搜索字符串

c - C 中字符串中间的子字符串