#include <iostream>
using namespace std;
int ft_strlen(char *str, char ascii[])
{
int i = 0;
while (!ascii[(short)str[i]] && str[i])
i;
return (i);
}
int word_count(char *s, char *ascii) {
int i = 0, cnt = 0;
while (s[i])
{
if (ascii[(short)s[i]])
while (ascii[(short)s[i]])
i;
else {
cnt;
while (!ascii[(short)s[i]] && s[i])
i;
}
}
return (cnt);
}
char **ft_strsplit(char *s, char *ascii) {
if (!s)
return NULL;
int wc = word_count(s, ascii);
char **ans = (char **)malloc(wc);
char *result;
int i = 0, j = 0, k;
while (wc--) {
result = (char *) malloc(ft_strlen(s i, ascii) 1);
for (k = 0; s[i] != '\0'; i, k) {
if (!ascii[(short)s[i]])
result[k] = s[i];
else {
result[i] = '\0';
ans[j ] = result;
//inside the printf
printf("%d %s\n", j - 1, ans[j - 1]);
while (ascii[(short)s[i]])
i;
break;
}
}
result[i] = 0;
ans[j] = result;
}
for (int i = 0; i < 5; i) {
printf("%d %s\n", i, ans[i]);
}
return ans;
}
int main()
{
char ascii[256] = {0,};
char d[] = ", ";
int i = -1;
while (d[ i])
ascii[(short)d[i]] = 1;
char str[90] = "it, is my, day 2,";
char** ptr = ft_strsplit(str, ascii);
for (int i = 0; i < 5; i) {
printf("%d %s\n", i, ptr[i]);
}
return 0;
}
我拆分字串并列印它們,在 printf 內部列印得很好(請看評論)但是另一個 printf 的第一個字串輸出很奇怪.. 我不知道為什么會這樣。下面是這段代碼的輸出。
0 it
1 is
2 my
3 day
4 2
0 8P
1 is
2 my
3 day
4 2
0 8P
1 is
2 my
3 day
4 2
我希望所有 printf 輸出都像
0 it
1 is
2 my
3 day
4 2
我在https://cpp.sh/這個網站上試過這個代碼。如果這個輸出取決于編譯器請告訴我。
uj5u.com熱心網友回復:
自從我撰寫 C 代碼以來,已經有好幾年了,但據我回憶,這一行:
char **ans = (char **)malloc(wc);
當您實際上需要指標的長度時,只會為字串中的每個單詞提供一個位元組。我相信你真正想要的是:
char **ans = (char **)calloc(wc, sizeof(char*));
另外,你為什么要費心學習C?即使你忽略它的面向物件特性,C 也是一個“更好的 C”(這是它的設計目標之一),并為你提供bool.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/522375.html
標籤:C strsplit
上一篇:具有多個可變引數的函式是什么?
