[英]C function for separate a string in array of chars
我想創建一個函數來分割使用C.兩個參數的分隔符文本text
和separator
將被傳遞給函數和函數應返回的array of chars
。
例如,如果字符串是Hello Word of C
且分隔符是white space
。
然后函數應該返回,
0. Hello
1. Word
2. of
3. C
作為字符數組。
有什么建議么?
strtok是否不符合您的需求?
正如其他人已經說過的:不要指望我們編寫您的作業代碼,但這是一個提示:(如果允許您修改輸入字符串)請考慮一下這里發生的情況:
char *str = "Hello Word of C"; // Shouldn't that have been "World of C"???
str[5] = 0;
printf(str);
好吧,與abelenky相同的解決方案,但是沒有無用的廢話和測試代碼的混淆(當諸如printf之類的東西應該寫兩次時,我不會引入虛擬布爾值來避免它,我沒有在某處讀到類似的東西?)
#include<stdio.h>
char* SplitString(char* str, char sep)
{
return str;
}
main()
{
char* input = "Hello Word of C";
char *output, *temp;
char * field;
char sep = ' ';
int cnt = 1;
output = SplitString(input, sep);
field = output;
for(temp = field; *temp; ++temp){
if (*temp == sep){
printf("%d.) %.*s\n", cnt++, temp-field, field);
field = temp+1;
}
}
printf("%d.) %.*s\n", cnt++, temp-field, field);
}
在Linux下用gcc測試:
1.) Hello
2.) Word
3.) of
4.) C
我的解決方案(通過@kriss解決評論)
char* SplitString(char* str, char sep)
{
char* ret = str;
for(ret = str; *str != '\0'; ++str)
{
if (*str == sep)
{
*str = '\001';
}
}
return ret;
}
void TestSplit(void)
{
char* input = _strdup("Hello Word of C");
char *output, *temp;
bool done = false;
output = SplitString(input, ' ');
int cnt = 1;
for( ; *output != '\0' && !done; )
{
for(temp = output; *temp > '\001'; ++temp) ;
if (*temp == '\000') done=true;
*temp = '\000';
printf("%d.) %s\n", cnt++, output);
output = ++temp;
}
}
在Visual Studio 2008下測試
輸出:
1.) Hello
2.) Word
3.) of
4.) C
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.