[英]Creating a dynamic array of char* from a char* text using strtok_s
[英]Not getting tokenized array from strtok_s()
我正在嘗試使用 strtok_s() function 對數組進行標記化,但我還想包含對數組進行標記化的分隔符。 如果它是斜杠“/”,我希望數組在任何使用斜杠“/”字符制作的標記處都有斜杠。
我寫了一個 function,它接受字符串和分隔符並返回另一個帶有標記和分隔符的字符串。
但是,它沒有按預期工作,我不知道為什么。 另外,我不太擅長 C 語言。
任何正確方向的幫助或指導將不勝感激。
下面是我的主要 cpp 文件和控制台 output
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct token_stat {
int n; // for total items in array
char* r_array; // pointer to the array returned from function
};
// function for passing a string and a delimeter and getting back
// the array with tokenized items including the delimeter
token_stat append_token_delim(char* string_in, char splitter[])
{
token_stat result;
char* token = NULL ; // initialize variables for STRTOK_S func
char* next_token = NULL ;
char* token_accum = (char*)malloc(2*sizeof(string_in)) ; // allcate memory twice that of the string we are tokenizing
char* delim = splitter; // pointer to the delimeter in main function
int i = 0;
token = strtok_s(string_in, delim, &next_token); // first call and getting the token
while (token != NULL)
{
token_accum[i] = token[0]; // add the token to token_accum array
token_accum[i + 1] = *delim; // now add the delimeter character next to the 1st token
printf("%s\t%s\n", token, delim); // print token and the delimeter
token = strtok_s(NULL, delim, &next_token); // make call again to strtok to get next token
i = i + 2; // increment index by 2 to get to the next token
}
int numberOfTokens = sizeof(*token_accum) / sizeof(token_accum[0]); // get total items in token_accum array for printing in main
result.n = numberOfTokens; // passing values to TOKEN_STAT STRUCT
result.r_array = token_accum; // passing the array to STRUCT
return result; // returning the struct back
}
// printing the array
void print_tokens(token_stat in_array)
{ printf("Number of Tokens in Array; %d", in_array.n);
}
int main()
{
char str[] = "- Thi;s,ansample()str;ing.";
token_stat main_accum;
char delimeter = '/';
main_accum = append_token_delim(str, &delimeter);
print_tokens(main_accum);
return 0;
}
您想在 token_accum 中存儲多個字符串,但您只存儲第一個字符token_accum[i] = token[0];
要存儲多個字符串,您需要一個指針數組,您可以像這樣存儲字符串
token_accum[i] = token;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.