2012-09-13 36 views
2
#include <stdio.h> 
int 
main() { 
    char string[] = "my name is geany"; 
    int length = sizeof(string)/sizeof(char); 
    printf("%i", length); 
    int i; 
    for (i = 0; i<length; i++) { 

    } 
    return 0; 
} 

如果我想打印“我的”“名称”“是”和“geany”分开,那么我该怎么办。我想用一个delimnator,但我不知道如何通过人物与指针做在C如何在不使用strtok的情况下拆分C中的字符串

+2

为什么不用'strtok'? – Tudor

+1

这是功课吗? –

+0

我正在探索C,我碰到了这个 – larzgmoc

回答

4
  1. 开始到字符串的开头
  2. 迭代特性,寻找您的分隔符
  3. 每当你找到一个,你有一个字符串从长度的最后一个位置的差异 - 做你想要的,
  4. 设置新的开始位置的分隔符+1,并转到第2步。

在字符串中剩余字符的同时执行所有这些操作...

0
use strchr to find the space. 
store a '\0' at that location. 
the word is now printfable. 

repeat 
    start the search at the position after the '\0' 
    if nothing is found then print the last word and break out 
    otherwise, print the word, and continue the loop 
0

重新创建轮子通常是一个糟糕的主意。学习使用实现功能也是一个很好的培训。

#include <string.h> 

/* 
* `strtok` is not reentrant, so it's thread unsafe. On POSIX environment, use 
* `strtok_r instead. 
*/ 
int f(char * s, size_t const n) { 
    char * p; 
    int ret = 0; 
    while (p = strtok(s, " ")) { 
     s += strlen(p) + 1; 
     ret += puts(p); 
    } 
    return ret; 
} 
0

这会在换行符处打断一个字符串,并为报告的字符串修剪空格。它不会像strtok那样修改字符串,这意味着这可以在未知来源的const char*上使用,而strtok不能。所不同的是begin/end是指向原始字符串字符的指针,所以不会像strtok给出的以null结尾的字符串。当然这使用静态本地,所以不是线程安全的。

#include <stdio.h> // for printf 
#include <stdbool.h> // for bool 
#include <ctype.h> // for isspace 

static bool readLine (const char* data, const char** beginPtr, const char** endPtr) { 
    static const char* nextStart; 
    if (data) { 
     nextStart = data; 
     return true; 
    } 
    if (*nextStart == '\0') return false; 
    *beginPtr = nextStart; 

    // Find next delimiter. 
    do { 
     nextStart++; 
    } while (*nextStart != '\0' && *nextStart != '\n'); 

    // Trim whitespace. 
    *endPtr = nextStart - 1; 
    while (isspace(**beginPtr) && *beginPtr < *endPtr) 
     (*beginPtr)++; 
    while (isspace(**endPtr) && *endPtr >= *beginPtr) 
     (*endPtr)--; 
    (*endPtr)++; 

    return true; 
} 

int main (void) { 
    const char* data = " meow ! \n \r\t \n\n meow ? "; 
    const char* begin; 
    const char* end; 
    readLine(data, 0, 0); 
    while (readLine(0, &begin, &end)) { 
     printf("'%.*s'\n", end - begin, begin); 
    } 
    return 0; 
} 

输出:

'meow !' 
'' 
'' 
'meow ?' 
1

我需要做到这一点,因为环境是工作中有这样缺乏strtok一个有限的库。以下是我打破了连字符分隔的字符串:

 b = grub_strchr(a,'-'); 
    if (!b) 
     <handle error> 
    else 
     *b++ = 0; 

    c = grub_strchr(b,'-'); 
    if (!c) 
     <handle error> 
    else 
     *c++ = 0; 

这里,a开始生活为复合字符串"A-B-C",代码执行后,有三个空值终止字符串,abc具有值"A""B""C"<handle error>是用于对缺少分隔符作出反应的代码的持有者。

请注意,与strtok类似,通过用NULL替换分隔符来修改原始字符串。

相关问题