在C中复制字符数组?

时间:2016-02-20 22:25:59

标签: c arrays string character

我有一个大小为81的数组被传递给result参数,但该程序结束时该数组尚未被修改。例如,输入为<form name="test" action="test-search.php" method="POST"> <input id="MemberIDs" name="MemberIDs" type="text" value="100,107"> <input type="submit" name="Submit" value="SUBMIT" /> </form> ,结果字符串应为" city "。我在某处错误地复制了字符吗?

"city"

5 个答案:

答案 0 :(得分:0)

在您的代码中:

   last = first;
    printf("FIRST: %d\n" , first);
    for(i= first; i< length; i++){
        if(source[i] == ' '){
          last = i-1;
          break;
        }
    }

如果没有空格会怎么样?没有。最后==第一。因此,如果您的第一个字符不是空格,则first = 0.如果没有遇到空格,则last = first。这意味着last = first = 0。

所以:

    for(i=first; i<= last; i++){
      result[i] = source[i];

...除了复制第一个字符外什么都不做。将代码更改为:

   last = first;
    printf("FIRST: %d\n" , first);
    for(i= first; i< length; i++){
        if(source[i] != ' '){
          last = i;
        }
        else break;
    }

答案 1 :(得分:0)

如果您正在尝试修剪字符串(修剪字符串意味着从字符串中删除空格和字符串末尾,例如s =" Hello World "; 结果将是&#34; Hello World&#34;) 所以你的错误就是你只删除了第一个空格" Hello World" 将是" Hello World" 所以你必须这样做才能指定结果字符串的第一个字符

//remove the white spaces from the begging of the string 
    int i =0 ;
    while( i < length && source[i] == ' ') i++;
    int first = i ;
    //remove the white spaces from the end of the string 
    i = length -1 ;
   while( i >= 0 && source[i] == ' ') i--; 
   int end = i ; 
   int j =0 ; 
   for( i = first ; i <= end ; i ++ ) result[j++] = source[i]; 
   result[j] = '\0';

否则,如果你想要删除字符串中的所有空格,你可以这样做:

int i = 0 , j =0 ; 
for(i =0 ; i < length ; i ++ ) { 
   if(source[i] != ' ' ) result[j++] = source[i]; 
}
result[j] = '\0'; 

我希望这对你有用

答案 2 :(得分:0)

下面的函数trimmer()修剪前导和尾随字符串中的空格。我将其添加到zString代码中:)

函数使用检查变量(int in_word)来判断它是否在单词内。 复制所有字符,包括到目的地的空格。保存最后一个&#34;非白色空间的索引&#34;字符并使用此索引值终止字符串。

#include <stdio.h>
#include <stdlib.h>

char *trimmer(char *str){
    char *src=str;  /* save the original pointer */
    char *dst=str;  /* result */
    int in_word=0;  /* logical check */
    int index=0;    /* index of the last non-space char*/

    while (*src)
        if(*src!=' '){
         /* Found a word */
            in_word = 1;
            *dst++ = *src++;  /* make the assignment first
                               * then increment
                               */
        } else if (*src==' ' && in_word==0) {
         /* Already going through a series of white-spaces */
            in_word=0;
            ++src;
        } else if (*src==' ' && in_word==1) {
         /* End of a word, dont mind copying white-spaces here */
            in_word=0;
            *dst++ = *src++;
            index = dst-str; /* save the location of the last char*/
        }

    /* terminate the string */
    *(str+index)='\0';

    return str;
}

int main()
{
    char s[]="     Hello world!     ";
    printf("%s\n",trimmer(s));
    return 0;
}

theis代码的输出是

Hello World!

答案 3 :(得分:0)

Jenny,我不确定你是否需要按照任务的角度处理问题,但如果没有,有几件事可以使你的方法更容易一些。

首先,您正在处理以空字符结尾的字符串。因此,为了操作字符串中的任何字符,不需要计算独立的长度。您可以简单地遍历字符串中的字符(使用索引指针,直到到达 nul-terminatedating 字符为止。无需单独的getlength功能。

接下来,当您查看strlen时,它会返回size_t类型而不是类型intsize_t仅限于int类型的正值,但在处理长度时更有意义,因为您不能拥有个字符数。此外,通过选择合适的类型,可以使getlength函数与期望获得size_t个字符数的所有标准库函数兼容(无需强制转换

remove_spaces函数中出现类似的类型(和参数)不匹配。在处理字符串操作函数时,它们通常返回指向char *的指针,以使函数的结果可分配,或者直接在任何带指针的函数中使用。 (例如printf ("reversed string : %s\n", remove_spaces (old_string, new_string));

虽然很明显你传递指针int *status作为在调用函数中指示成功/失败的一种方式,但处理字符串时的成功或失败通常由要么返回有效的char *字符串,要么返回NULL。这是使remove_spaces类型char *代替void的另一个主要理由。此外,返回指向有效字符串的指针,或者只需NULL来指示函数的成功/失败,从而完全不需要int *status

以这种方式接近remove_spaces,您可以决定是否要使用指针和索引实现它,或者是否要依赖一个或多个标准库函数。例如,根据您输入的输入长度,您可能需要一种完全不同的方法。

如果您的输入字符串仅限于单字,请查看标准函数sscanf以及%s 格式说明符。当%s用于解析单字字符串时,忽略前导空格并在第一个试用空格时停止转换遇到。在这种情况下,将sscanfremove_spaces放在一起使用,你可以做一些简单的事情,比如

char *remove_spaces_word (const char *source, char *result)
{
    if (sscanf (source, "%s", result) == 1)
        return result;
    else
        return NULL;
}

当然,你可能会输入包含很多单词的内容。使用字符串时,有时在字符串中的每个字符上推进指针比使用 array-index 尝试访问每个字符要少得多。它还消除了跟踪索引的加法和减法。您可能还会发现指针是一种更自然的方式来处理字符串中的字符。

要处理从任何字符串中删除空格,无论涉及的字数是多少,使用指针而不是索引的方法可能如下所示:

char *remove_spaces (const char *s, char *r)
{
    if (!s || !*s) return NULL;             /* validaate source str      */
    char *p = r;                            /* pointer to result         */
    *r = 0;                                 /* initialize as empty str   */
    while (isspace (*s))  s++;              /* skip leading whitespace   */
    for (; *s; s++, p++) *p = *s;           /* fill r with s to end      */
    *p = 0;                                 /* nul-terminate r           */
    while (p > s && isspace (*--p)) *p = 0; /* overwrite spaces from end */

    return r;
}

你可以看到它是如何工作的。如果s 为空NULL,则会返回NULL。然后为指针p分配r的地址(结果)。 isspace函数(在ctype.h中)用于跳过所有前导空格,直到找到第一个非空格字符(s未指向第一个你要保留的角色)。然后将s整个剩余部分(包括所有尾随空格)复制到rr nul-terminated 。最后,r肯定是 nul-terminated ,然后使用p从末尾回溯,用 nul-terminatedating 字符覆盖所有尾随空格0

注意:实现这样的函数可能有20种不同的方法。 strchrstrrchrstrpbrkstrspnstrcspn等功能都可用于帮助在指针的开头或结尾找到指针。字符串中的字符。没有一个&#34;正确的方式&#34;解决这个问题。你的方法很好,它只是一种长途跋涉,而且一般来说,方法越长越多,错误就越多。

在这里查看所有答案并查看不同的方法。比较/对比它们。查看其他可用功能,并尝试根据需要以多种不同方式编写功能。通过各种方式尝试并考虑用户可以搞砸输入的所有不同方式,并尝试制定涵盖所有情况的解决方案。 (总是会有一两个你不考虑的角落,所以尝试和测试尽可能多的输入组合)没有替代或更好的方法来熟悉C的一个方面而不仅仅是尝试不同的方法。最后,选择最适合您情况的那个。祝你好运。

答案 4 :(得分:0)

  

我有一个大小为81的数组被传递给result参数但是   该程序结束时该数组尚未修改。

事实并非如此;见下文。

  

我在某处错误地复制了字符吗?

确实你是。使用示例来源   city    first在复制循环中为3且last 6

        for (i = first; i <= last; i++) {
            result[i] = source[i];
        }

- 因此您将city复制到result[3]result[6]。当您检查result 的长度时,正如您所说已初始化(至\0 s,我推测),它来了out为0 ,因为result[0]\0

当然,您打算从city开始将result复制到result[0],这可以通过

完成
        for (i = first; i <= last; i++) result[i-first] = source[i];