将字符串的一部分复制到另一个字符串

标签 c string

我有一串单词,它们之间有单词分隔符,在另一个字符串中,我想将主字符串的单词逐个放入,将单词与其他字符串进行比较,然后将其放入字符串数组中。

所以基本上我有 1)单词数组,以及 2)一串单词 其形式为 (word-word-word...),我需要做的是检查这些单词之一是否在单词数组中。如果是的话,删除它。 我将如何做到这一点是通过定义一个新的“char”类型变量,遍历我的主句子,只要我没有到达单词分隔符,我就会将该单词添加到新字符串中。使用另一个函数,我检查数组中是否存在这个单字字符串。如果不是,我将单词添加到临时数组中,然后释放字符串并重复直到句子结尾。但我似乎做不好(我刚刚开始研究字符、字符数组等主题)

void delete_words(char *words[],int n, char *sentence ){
int m=strlen(sentence);
char tmp[m];
char * str=(char*)malloc(sizeof(char)*(MAX_LEN));
int i=0,end=0,k,z;
for(k=0; k<m; k++)
{
    z=0;
    while(*sentence && sentence[i]!= WORD_SEPERATOR)
    {
        str[z]=sentence[i];
        i++;
        z++;
    }

    if(is_string_in_array(words,n,str)==false)
    {
        int len=strlen(str);
        strcpy(tmp+k,str);
        end=end+len;
        tmp[end]=WORD_SEPERATOR;
        free(str);
    }}

我确实意识到这是完全错误的,我可以找到一些错误,但我不知道如何修复它,因为正如我所说,这是我关于该主题的第一份作业。将非常感谢您的帮助!

最佳答案

这里 select_next_word 将迭代字符串并尝试逐个提取单词,然后我们对照数组检查它,如果不存在,我们将其添加到目标字符串

#include <stdio.h>
#include <String.h>

void select_next_word(char **buffer, char **next_word)
{
    *next_word = *buffer;
    while(**buffer != 0)
    {
        if(**buffer == '-')
        {
            **buffer = 0;
             (*buffer)++;
            break;
        }

        (*buffer)++;
    }
}

int main()
{
    #define CHECK_ARR_SIZE  2
    char check_arr[CHECK_ARR_SIZE][32] = {"this", "test"}; //make second dim large enough
    char test[] = "this-is-a-test-string";
    char dest[32]; //be sure it is large enough
    char *next_word;
    char *temp = test;

    while(1)
    {
        select_next_word(&temp, &next_word);
        int i = 0;
        int word_found = 0;
        for( ; i < CHECK_ARR_SIZE ;i++)
        {
            if(strcmp(next_word, check_arr[i]) == 0)
            {
                word_found = 1;
                break;
            }
        }

        if(!word_found)
        strcat(dest, next_word);
        if(*temp == 0)
         break;
    }

    printf(dest);
}

关于将字符串的一部分复制到另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54157141/

相关文章:

c - 如何编辑字符数组的某些部分

c - 构建一个使用 c 代码库的 R 包

c - 它出现在 c 中的字符串数组 (null)

linux - Bash 脚本 : Replace (or delete) string in a file if line starts with (or matches) another string

javascript - 检查文本是否包含序列。字符的相邻性不是必需的

c - 如何使这个非常小的 C 程序更快?

Linux/Windows 中的 C/C++ 内存使用 API

c++ - 使用指针的 strcat 实现

java - 字符串数组的元素无法与字符串进行比较

python - 使用 python 正则表达式模块将值替换为先前出现的首字母缩略词