如何使用两个正斜杠提取字符串

时间:2015-10-19 11:30:25

标签: c strstr

我有一个字符串,它总是有两个正斜杠/709/nviTemp1 我想从该字符串中提取/709/并将其返回char *,我将如何为此目的使用strstr?

我也可能在路径中有许多正斜杠,例如/709/nvitemp1/d/s/

所以我只需要获得第一个令牌/709/

4 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情:

char str[100] = "/709/nviTemp1";
char resu[100];
char *tmp;

tmp = strchr(str+1, '/');
strncpy(resu, str, (size_t)(tmp - str) + 1);
resu[(size_t)(tmp - str) + 1] = '\0';

strchr搜索第一个' /',但从str+1开始跳过真正的第一个。然后计算"尺寸" beetween start and found' /'并使用strncpy复制内容,并添加一个尾随' \ 0'。

答案 1 :(得分:2)

尝试使用strtokstrtok根据分隔符将字符串拆分为不同的标记。像这样:

char str[100] = "/709/nviTemp1";
char delimiter[2] = "/";
char *result;
char *finalresult;

result = strtok(str, delimiter); // splits by first occurence of '/', e.g "709"
strcat(finalresult,"/");
strcat(finalresult, result);
strcat(finalresult,"/");
printf("%s",finalresult);

请注意strtok会修改您传递给它的原始字符串。

答案 2 :(得分:1)

要执行您所询问的任务,以下代码就足够了。如果您需要更通用的解决方案,答案显然会有所不同。

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

int main()
{
    char *str = "/709/nviTemp1";
    char *delims = "/";
    char *strCopy;

    char *tmpResult;

    strCopy = strdup(str);
    tmpResult = strtok(strCopy, delims);

    // +1 for the first slash, +1 for the second slash, + another for the terminating NULL
    char *finalResult = (char*)calloc(strlen(tmpResult) + 3, 1);

    strcat(finalResult, "/");
    strcat(finalResult, tmpResult);
    strcat(finalResult, "/");

    free(strCopy);

    printf("%s",finalResult);
}

<强>输出:

  

/ 709 /

答案 3 :(得分:1)

使用strchr查找第一个斜杠。前进指针并找到第二个斜杠。前进指针并设置为'\0'

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

int main (int argc , char *argv[]) {
    char *tok;
    char text[] = "/709/nvitemp1/d/s/";

    if ( ( tok = strchr ( text, '/')) != NULL) {//find first /
        tok++;
        if ( ( tok = strchr ( tok, '/')) != NULL) {//find second /
            tok++;
            *tok = '\0';
            printf ( "%s\n", text);
        }
    }
    return 0;
}
相关问题