提问者:小点点

如何在不使用strtok和strlen函数的情况下编写代码


字符串的使用如何在不使用(strtok)和(strlen)函数的情况下编写代码,如何替换它们?

#define _CRT_SECURE_NO_WARNINGS 
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <string>
using namespace std;

int main()
{
char str[50];                  

char* temp;             

cout << "Input string: ";

cin.getline(str, 50, '\n');       

temp = strtok(str, " "); // temp адресс первого пробела

while (temp != NULL)           
{
    if (strlen(temp) % 2 == NULL)           
        cout << temp << '\t';

    temp = strtok(NULL, " ");
}

return 0;

}

共1个答案

匿名用户

strTokstrlen都是具有良好的C++替代方案的C-ism,例如使用流和字符串。

此外,在偶数长度字符串的测试中,null不应用作数字0

#include <iostream>
#include <sstream>
#include <string>

using std::cin;
using std::cout;
using std::getline;
using std::string;
using std::stringstream;

int main() {
    cout << "Input string: ";
    auto s = string{};
    getline(cin, s);

    auto ss = stringstream{s};
    auto word = string{};
    char const* sep = "";

    while (ss >> word) {
        if (word.length() % 2 == 0) {
            cout << sep << word;
            sep = "\t";
        }
    }

    cout << "\n";
}