#include <stdio.h>
#include<string.h>
int main() {
char a[]="hey -* there -* minecraft-; jukebox! "。
char *p=strtok(a,"-") 。
//printf("%s",a); --line-id(00)。
while(p!= NULL)
{
printf("%s",p); //line-id(01).
p=strtok(NULL,"-")。
}
printf("
")。)
p=strtok(a,"*"/span>)。
while(p!=NULL)
{
printf("%s"/span>,p)。
p=strtok(NULL,"*") 。
}
return 0;
輸出:
hey * there * Minecraft; jukebox!
咦?
但我需要的輸出是:
hey * there * Minecraft; jukebox!
嘿,Minecraft的點唱機!
Q) 為什么我不能把line-id(01)改成 print("%s",*p)因為p是一個指標,我們應該用*p來獲取值,p指向右邊。我得到一個分段故障。
Q)如果我使用print("%s",a),我在line-id(00)中得到hey作為輸出;為什么?
Q)如果可能的話,請解釋strtok()中使用的指標p。strtok是如何作業的?
uj5u.com熱心網友回復:
strtok()修改了輸入字串。先把它復制出來。strdup()是你的朋友。
如果你的編譯器抱怨說找不到strdup(),請復制/粘貼這個。
char *strdup(const char *s)
{
size_t len = strlen(s) 1;
char *t = malloc(len)。
if (!t) return NULL;
memcpy(t, s, len)。
return t。
}
uj5u.com熱心網友回復:
從char陣列中移除定界符的另一個選擇是用隨后的字符覆寫定界符,收縮陣列。
#include <stdio.h>
#include<string.h>
int main() {
char a[]="hey -* there -* minecraft-; jukebox! "。
char delimeters[] = "-*;";
char *to = a;
char *from = a;
for ( int each = 0; each < 3; each) {//loop through delimiters
to = a;
from = a;
while ( *from) {//not at terminating Zero
while ( *from == delimeters[each]) {
from;//推進指標經過分隔符。
}
*to = *from;//分配字符,根據需要覆寫。
to;
from;
}
*to = 0;//terminate。
printf ( "%s
", a)。)
}
return 0;
}
輸出
hey * there * minecraft; jukebox!
嘿,那里的Minecraft; 點唱機!
嘿,那里的Minecraft點唱機!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315457.html
標籤:
