在c中的字符串和字符串数组操作在

问题描述:

我想在C中写一个字符串分割函数。它使用空格作为分隔符来分割两个或多个给定的字符串。它更像Python.Here分割funtion是代码: -在c中的字符串和字符串数组操作在

#include <stdio.h> 
#include <string.h> 


void slice_input (char *t,char **out) 
{ 
    char *x,temp[10]; 
    int i,j; 
    x = t; 
    j=0; 
    i=0; 
    for (;*x!='\0';x++){ 
     if (*x!=' '){ 
      temp[i] = *x; 
      i++; 
     }else if(*x==' '){ 
      out[j] = temp; 
      j++;i=0; 
     } 
    } 
} 

int main() 
{ 
    char *out[2]; 
    char inp[] = "HEllo World "; 

    slice_input(inp,out); 
    printf("%s\n%s",out[0],out[1]); 
    //printf("%d",strlen(out[1])); 
    return 0; 
} 

Expeted输出: -

HEllo 
World 

,但它显示: -

World 
World 

你能帮助请?

+2

可能调试器是你的朋友 –

out[j] = temp;

其中temp是一个局部变量。只要你的函数终止,它就会超出范围,因此out[j]将指向垃圾,调用未定义行为被访问时。

一个简单的修正将是使用一个二维数组用于out,并使用strcpy()temp字符串复制到out[j],像这样:

#include <stdio.h> 
#include <string.h> 

void slice_input(char *t, char out[2][10]) { 
    char *x, temp[10]; 
    int i,j; 
    x = t; 
    j=0; 
    i=0; 
    for (;*x!='\0';x++) { 
    if (*x!=' ') { 
     temp[i] = *x; 
     i++; 
    } else if(*x==' ') { 
     strcpy(out[j], temp); 
     j++; 
     i=0; 
    } 
    } 
} 


int main() 
{ 
    char out[2][10]; 
    char inp[] = "HEllo World "; 

    slice_input(inp,out); 
    printf("%s\n%s",out[0],out[1]); 
    return 0; 
} 

输出:

HEllo 
World 
+0

这是正确的,但我认为这将是更好地为OP使用的strtok()soluion –

+3

@KrzysztofSzewczyk的OP希望实现自己的' strtok()',可能是为了练习。 – gsamaras

+0

只需检查strtok在线源代码! –

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

来自网站:

char * strtok(char * str,const char * delimiters);在第一个 调用中,该函数需要一个C字符串作为str的参数,其第一个 字符被用作扫描令牌的起始位置。在后续调用中,该函数需要一个空指针,并将位于最后一个标记结束之后的 位置作为新的起始 位置进行扫描。

一旦在调用 strtok中发现str的终止空字符,则此函数的所有后续调用(空指针为第一个参数为 )将返回一个空指针。

参数

str C要截断的字符串。请注意,该字符串被修改为 分解为较小的字符串(标记)。可选地[原文如此],可以指定空指针,在这种情况下,该功能继续 扫描,其中对该函数的先前成功调用结束。 分隔符C包含分隔符的字符串。这些可能 因呼叫而异。返回值

指向在字符串中找到的最后一个标记的指针。如果没有令牌可供检索,则返回空指针 。

/* strtok example */ 
#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char str[] ="- This, a sample string."; 
    char * pch; 
    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str," ,.-"); 
    while (pch != NULL) 
    { 
    printf ("%s\n",pch); 
    pch = strtok (NULL, " ,.-"); 
    } 
    return 0; 
} 

您可以使用此功能来分割字符串为标记 - 有没有必要一定要用自己的功能。你的代码看起来像垃圾,请格式化它。 你的源propably应该是这样的:

char * 
strtok(s, delim) 
    char *s;   /* string to search for tokens */ 
    const char *delim; /* delimiting characters */ 
{ 
    static char *lasts; 
    register int ch; 

    if (s == 0) 
    s = lasts; 
    do { 
    if ((ch = *s++) == '\0') 
     return 0; 
    } while (strchr(delim, ch)); 
    --s; 
    lasts = s + strcspn(s, delim); 
    if (*lasts != 0) 
    *lasts++ = 0; 
    return s; 
} 
+0

其实我想做一个像python溢出的功能,在那里我提到分隔符amd它将返回一个标记数组,而不使用库函数.Btw感谢您的帮助 –

+0

我给了你strtok的源代码,就拿它.. –

+0

是的,我试图理解,只有...谢谢你 –