c++ - 有没有更好的方法来为 C++ 编写这个?

标签 c++ string substring c-strings

<分区>

目标是通过提取由空格分隔的单词,从输入的字符串中创建子字符串。

子串本身必须是变量。

听起来很简单,但困难在于您只能使用 strcpy、strcmp、strlen、strcat、strncpy、strncmp、strnlen 和 strncat。

例子:

输入:

“约翰 40 killer ”

司机:

...

cout << word1 << endl 
     << word2 << endl 
     << word3 << endl;

输出:

John
40
Hitman

这是我的代码

#include <iostream>
#include <cstring>
#include <stdio.h>

int main(){

const char *string = "Name Age Job";
char name[10];
char age[10];
char job[10];
int length = strlen(string);
int temp = 0;
bool flag = false;

for(int i = 0; i < length + 1; i++){
  if(isspace(string[i]) && !flag){
    strncpy(name, string, i);
    name[i] = '\0';
    temp = i;
    flag = !flag;
    cout << name << endl;
    continue;
  }
  if(isspace(string[i])){
    strncpy(age, string + temp + 1, length - i - 1);
    age[temp - i] = '\0';
    temp = i;
    cout << age << endl;
    continue;
  }
  if(string[i] == '\0'){
    strncpy(job, string + temp + 1, length);
    job[temp - i] = '\0';
    cout << job << endl;
  }
}

它有效,但它必须使用标志 bool 值,字符串不是动态的,仅适用于具有 2 个空格的字符串,并且有很多重复代码。总的来说真的很糟糕,但我花了大约两个小时在这上面,我不知道如何改进它。

如果你想知道,这确实是一道作业题,但这是一门入门课,我的教授只希望正确输出只有 3 个单词的硬编码字符串。但是,我想学习如何改进它,如果有任何帮助,我将不胜感激。谢谢。

最佳答案

您需要做的就是替换空格 ' ''\0' (字符串结尾)从而从原始字符串创建 3 个子字符串。以下程序执行此操作并将字符串转储到 cout但您也可以将指针保存在数组中(例如 char* substring[3] )。

int main(){
    char string[] = "Name Age Job";
    char* temp = string;
    for(char* it = string; *it; ++it ) {
        if (*it == ' ') {
            *it = '\0';
            std::cout << temp << std::endl;
            temp= it + 1;
        }
    }
    std::cout << temp << std::endl;
}

关于c++ - 有没有更好的方法来为 C++ 编写这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58989410/

相关文章:

c++ - 如何更新 C++ 中的自定义日期?

c++ - 将对象指向 NULL 会将成员值置于什么位置?

c++ - C++ 中非常快速的近似对数(自然对数)函数?

c - 从字符串中删除一个字符

javascript - 仅从 10.0 或 2 获取数字

c++ - c++中的开关中断故障怎么办?

c++ - 为什么在 std::cout 上显式调用 operator<< 会导致意外输出?

c# - 我们如何通过位置和分隔符提取字符串的子字符串

Python 在字符串开头匹配 '.\'

javascript - js中克隆的substring()函数出错