c - 从 char 数组中删除第一个单词并使用 C 中的指针将其打印出来
问题描述
所以我正在尝试制作一个小程序,其中我有一个带有单词的字符串,我需要从中删除第 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');
}
解决方案
在您的代码中存在一些编译时错误。也就是说,您已经取消并使用void removeAll(char * str, char * toRemove);
了 function 而不是void removeWord(char * str, char * toRemove)
.
以下是更正的工作代码。看到它在这里工作:
#include <stdio.h>
#include <string.h>
void removeWord(char * str, char * toRemove);
int main(){
char words[100];
char origional[100];
char removeword[100];
printf("Enter your sentence: ");
gets(words);
printf("Enter word to delete: ");
gets(removeword);
strcpy(origional, words);
removeWord(words, removeword);
printf("\nWord before deleting: %s", origional);
printf("\nWord 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--;
}
}
}
输出:
Enter your sentence: Hello there how are you?
Enter word to delete: how
Word before deleting: Hello there how are you?
Word after deleting: Hello there are you?
推荐阅读
- css - 输入表单中的角度突出显示子字符串
- android - android [Flutter] 中的 Agora 屏幕共享问题
- sharepoint-online - 使用 MS Graph 在 SharePoint Online 文档库中上传/创建文件
- php - 明智地更改 dokan 商店 url 编号而不是存储 url
- javascript - 如何使用表单 javascript 检查值
- java - 无法打开指定的文件夹android R
- python - 我想对 python 字典进行 SQL 查询
- java - Vaadin Spring Boot - 尝试导航到“”时出现异常 - NoSuchBeanDefinitionException
- javascript - 如何使用时刻 js 延迟脚本运行?
- sql - 使用单个 LIKE 子句搜索多个模式