Ç的strtok()将字符串分割成标记,但保持原有数据不变 [英] C strtok() split string into tokens but keep old data unaltered

查看:148
本文介绍了Ç的strtok()将字符串分割成标记,但保持原有数据不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

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

int main (void) {
char str[] = "John|Doe|Melbourne|6270|AU";

char fname[32], lname[32], city[32], zip[32], country[32];
char *oldstr = str;

    strcpy(fname, strtok(str, "|"));
    strcpy(lname, strtok(NULL, "|"));
    strcpy(city, strtok(NULL, "|"));
    strcpy(zip, strtok(NULL, "|"));
    strcpy(country, strtok(NULL, "|"));

    printf("Firstname: %s\n", fname);
    printf("Lastname: %s\n", lname);
    printf("City: %s\n", city);
    printf("Zip: %s\n", zip);
    printf("Country: %s\n", country);
    printf("STR: %s\n", str);
    printf("OLDSTR: %s\n", oldstr);

return 0;
}

执行输出:

$ ./str
Firstname: John
Lastname: Doe
City: Melbourne
Zip: 6270
Country: AU
STR: John
OLDSTR: John

为什么我不能保留旧的数据,也不在 STR oldstr ,我在做什么错和哪能不改变数据或保持?

Why can't I keep the old data nor in the str or oldstr, what am I doing wrong and how can I not alter the data or keep it?

推荐答案

当你做的strtok(NULL,|) strtock找到令牌,并把空的地方(的更换令牌\\ 0 的)和修改字符串。

when you do strtok(NULL, "|") strtock find token and put null on place (replace token with \0) and modify string.

STR ,就变成了:

char str[] = John0Doe0Melbourne062700AU;

  Str array in memory 
+------------------------------------------------------------------------------------------------+
|'J'|'o'|'h'|'n'|0|'D'|'o'|'e'|0|'M'|'e'|'l'|'b'|'o'|'u'|'r'|'n'|'e'|0|'6'|'2'|'7'|'0'|0|'A'|'U'|0|
+------------------------------------------------------------------------------------------------+
                 ^  replace | with \0  (ASCII value is 0)

考虑图很重要,因为焦炭 0 0 是缺乏自信(字符串6270在图中 其中的 \\ 0 0是数字)

Consider the diagram is important because char '0' and 0 are diffident (in string 6270 are char in figure parenthesised by ' where for \0 0 is as number)

>约翰·

when you print str using %s it print chars upto first \0 that is John

要保留原来的STR不变应拳头副本海峡到一些tempstr变量,然后使用 tempstr 字符串的strtok()

To keep your original str unchanged you should fist copy str into some tempstr variable and then use that tempstr string in strtok():

char str[] = "John|Doe|Melbourne|6270|AU";
char* tempstr = calloc(strlen(str)+1, sizeof(char));
strcpy(tempstr, str);

现在在你的code使用 tempstr 字符串代替str的。

Now use this tempstr string in place of str in your code.

这篇关于Ç的strtok()将字符串分割成标记,但保持原有数据不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆