我们的教授给了我们一个回文作业,在这个作业中,我们需要编写一个函数,该函数删除所有标点符号,空格,并在c-string中将大写字母转换为小写字母。我遇到的问题是当我调试/运行它时,在为函数输入cstring之后,它会给出“ Debug Assertion failed”错误,并仅给出c字符串输入的小写字母版本的输出。有人建议我如何解决或改进这段代码吗?
更新:我通过像geeksforgeeks那样标记字符串来解决我的错误。但是现在我遇到的问题是,将s cstring的标记串联到new_s c字符串中时,它仅将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('\0', " ,.?!:;"); //tokenize rest of the string
}
while (tokenptr != NULL)
{
// concat rest of the tokens to a new cstring. include the \0 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, "..")
,而不是'\0'
。