将字符串复制到数组实现C

时间:2015-08-03 11:55:39

标签: c

我的问题如下:

编写一个函数int tokenCopy(char * dest,const char * src,int destSize),它将给定源字符串src中的字符复制到给定目标缓冲区dest中,其大小为destSize,直到:

发生源字符串的结尾,或

目标缓冲区已满(允许需要的终结符)或

在输入字符串中找到空格字符

以先到者为准。如果由于找到空格而完成复制,则不会复制空间。必须始终正确终止目标字符串。如果源字符串的目标空间不足,则目标字符串必须是源字符串的正确终止的前导子字符串。

返回值是复制的字符数,不包括终止空字节。

这是我到目前为止的尝试:

   int tokenCopy(char* dest, const char* src, int destSize)
   {
        int the_slab = 0;
        for (; *src != ('\0' | ' '); the_slab++) 
        {   
            if ( *src == (32 | 0)) 
            {
                *dest = '\0';
                return the_slab;
            }
            *dest = *src;
            dest++;
            src++;  
         }
        *dest = '\0';
        return the_slab;      
       }

然而,在通过以下方式测试时失败:

char buff[10];
int n = tokenCopy(buff, "This", 10);
printf("%d '%s'\n", n, buff);

因为它返回数字7而不是4。 在处理完前四个字母后,为什么不能终止?我不明白为什么src没有终止字节?

我做错了什么?我从概念上理解不了什么?

谢谢!

4 个答案:

答案 0 :(得分:4)

*src != ('\0' | ' ')没有按照您的想法行事。

您需要将其拆分为两个:

*src != '\0' && *src!= ' '

同样的:

  if ( *src == (32 | 0)) 

应该是:

 if ( *src == ' ' || *src )

使用字符表示' '总是比假设/依赖ASCII值更好。

实际上,循环内部的整个条件都是简化的:

   if ( *src == (32 | 0)) 
        {
            *dest = '\0';
            return the_slab;
        }

这就是你在for循环条件下测试的内容。

答案 1 :(得分:2)

|运算符对两个操作数执行按位“或”运算 - 完全不是你想要的。

C bitwise OR operations

您的测试应使用逻辑OR运算符||

if (*src == ' ' || *src == '\0')

答案 2 :(得分:2)

这确实是一条评论,但评论不允许正确的代码格式化。我同意@JohnPirie和@BlueMoon的答案。

这是一个使用数组索引更清晰然后使用指针的示例,如下面的代码所示:

int tokenCopy(char* dest, const char* src, int destSize)
{
    int i;
    if (dest == NULL || source == NULL || destSize < 1) {
        // invalid input!
        return -1;
    }
    for (i = 0; i < (destSize-1) && src[i] != '\0' && src[i] != ' '; i++) {   
        dest[i] = src[i];
    }
    dest[i] = '\0';
    return i;
}

答案 3 :(得分:0)

运算符|是bitwize(OR)运算符。 ( *src == (32 | 0))if ( *src == 32 )相同的说明。因为32|0==32; 记得逻辑表?:

0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1=  1

bitwize运算符将每个源的位与dest的位进行比较,并且因为0使所有位都关闭,所以32位中的每个位保持不变

你必须这样做才能起作用:

if ( (*src == 32) || (*src== 0)) { ...