将旧 cstring 的标记连接成新的 C 字符串



我们的教授给了我们一个回文作业,在这个作业中,我们需要编写一个函数来删除所有标点标记、空格,并将大写字母转换为c 字符串中的小写字母。 我遇到的问题是当我调试/运行它时,在我输入函数的 cstring 后,它给出了"调试断言失败"错误,并给出了仅小写字母版本的 c 字符串输入的输出。有没有人建议我如何修复或改进这段代码?

更新:我通过像极客一样标记字符串来修复我的错误。但是现在我遇到的问题是,当将 s cstring 的标记连接到c字符串new_s时,它只将s的第一个标记连接到new_s这是我的代码:

#define _CRT_SECURE_NO_WARNINGS //I added this because my IDE kept giving me error saying strtok is unsafe and I should use strtok_s. 
#include <iostream>
#include <iomanip>
#include <cstring>
using namespace  std;
/*This method removes all spaces and punctuation marks from its c-string as well as change any uppercase letters to lowercase. **/
void removePuncNspace(char s[])
{
char new_s[50], *tokenptr;
//convert from uppercase to lowercase
for (int i = 0; i < strlen(s); i++) (char)tolower(s[i]);
//use a cstring function and tokenize s into token pointer and eliminate spaces and punctuation marks
tokenptr = strtok(s, " ,.?!:;");
//concatenate the first token into a c-string.
strcpy_s(new_s,tokenptr);
while (tokenptr != NULL)
{
tokenptr = strtok('', " ,.?!:;"); //tokenize rest of the string
}
while (tokenptr != NULL)
{
// concat rest of the tokens to a new cstring. include the  NULL as you use a cstrig function to concatenate the tokens into a c-string.
strcat_s(new_s, tokenptr);
}
//copy back into the original c - string for the pass by reference.
strcpy(s, new_s);
}

我的输出是:

输入一行:
汉娜看到蜜蜂了吗?汉娜做到了!
做是回文

首先,正如 @M.M 所说,当您想继续标记同一字符串时,您应该调用strk(NULL, ".."),而不是使用''

其次,你的程序逻辑没有多大意义。您将字符串s拆分为子字符串,但从未真正将它们连接起来以new_s。当你到达第二个时,tokenptr肯定是NULL,所以你永远不会进入循环。

为了修复您的代码,我将两个 while 合并为一个 while,并添加了一个 if 以不调用strcat(new_s, tokenptr)如果tokenptr为 NULL。

void removePuncNspace(char s[])
{
char new_s[50], *tokenptr;
//convert from uppercase to lowercase
for (int i = 0; i < strlen(s); i++) (char)tolower(s[i]);
//use a cstring function and tokenize s into token pointer and eliminate spaces and punctuation marks
tokenptr = strtok(s, " ,.?!:;");
//concatenate the first token into a c-string.
strcpy(new_s,tokenptr);
while (tokenptr != NULL)
{
tokenptr = strtok(nullptr, " ,.?!:;"); //tokenize rest of the string
if (tokenptr != NULL)
strcat(new_s, tokenptr);
}
//copy back into the original c - string for the pass by reference.
strcpy(s, new_s);
}

PS:我使用了cstring函数的非安全版本,因为出于某种原因,我的编译器不喜欢安全版本。

最新更新