【发布时间】:2018-05-02 17:35:36
【问题描述】:
所以我正在尝试制作一个小程序,其中我有一个带有单词的字符串,我需要从中删除第 n 个单词,然后使用指针将其打印出来。
我做了一个可以删除第 n 个单词的部分,但我不明白如何使用指针打印它。
编辑(对不起,我忘了添加代码):
#include <stdio.h>
#include <string.h>
void removeAll(char * str, char * toRemove);
int main(){
char *words[100];
char removeword[100];
printf("Enter your sentence: ");
gets(words);
printf("Enter word to delete: ");
gets(removeword);
removeAll(words, removeword);
printf("Word after deleting: %s", words);
}
void removeWord(char * str, char * toRemove)
{
int i, j, stringLen, toRemoveLen;
int found;
stringLen = strlen(str);
toRemoveLen = strlen(toRemove);
for(i=0; i <= stringLen - toRemoveLen; i++)
{
found = 1;
for(j=0; j<toRemoveLen; j++)
{
if(str[i + j] != toRemove[j])
{
found = 0;
break;
}
}
if(str[i + j] != ' ' && str[i + j] != '\t' && str[i + j] != '\n' && str[i + j] != '\0')
{
found = 0;
}
if(found == 1)
{
for(j=i; j<=stringLen - toRemoveLen; j++)
{
str[j] = str[j + toRemoveLen];
}
stringLen = stringLen - toRemoveLen;
i--;
}
}
}
编辑 2:
char *pWord = words;
for (int i=0; pWord[i]; ++i) {
const char *ch = pWord[i];
while(*ch) {
putchar(*ch++);
putchar('\n');
}
putchar('\n');
}
【问题讨论】:
-
如果你能找到这个词,为什么你不能打印呢?也许在将其从字符串中删除之前将其复制到另一个数组。
-
显示尝试打印它的代码,我们不会为您编写。
-
gets(words);- 如果这没有用至少警告标记你的编译,如果不是完全错误,关于类型不匹配的指针,你真的需要提高你的警告级别。您还需要忘记您曾经听说过函数gets。它已从标准库中删除,应该从不使用。 -
除了
words的类型错误和removeWord被重命名为removeAll,它应该可以按预期工作。您究竟遇到了什么打印问题? -
我需要使用指针打印新数组,我试过但它给了我错误,我试过的代码是第二次编辑。