2015-12-22 18 views
0

我有這個功能:int split(char* str, char s),那麼如何拆分str而不使用strtok()或其他函數?如何分割字符數組而不使用任何基本功能

E.g:str = "1,2,3,4,5", s = ','split(str, s)

後,輸出將是:

1 
2 
3 
4 
5 

對不起球員,包括int返回-1如果str == NULL和如果str = NULL返回1!

+2

考慮字符串的'linked'字符序列,並在發現','你需要移動到印刷在新行 – nullpointer

+0

您正在尋找'join'? –

+0

這是C還是C++?該函數需要一個'char *'而不是'字符串'。 –

回答

0
string split(const char* str, char s) { 
    std::string result = str; 
    std::replace(result.begin(), result.end(), s, '\n'); 
    result.push_back('\n'); // if you want a trailing newline 
    return result; 
} 
+0

返回類型是一個'int',所以我猜他想要從函數中打印出分割的字符串。 –

+0

@TheObscure問題:這是可能的。我更喜歡讓函數的調用者說'cout << split(...)'或其他什麼。保持I/O與轉換分離。 –

+0

@JohnZwinck當功能程序員xD – Czipperz

3

這個怎麼樣?我不確定函數中的int返回類型是什麼意思,所以我把它作爲分割的計數。

#include <stdio.h> 
int split(char* str, char s) { 
    int count = 0; 
    while (*str) { 
     if (s == *str) { 
      putchar('\n'); 
      count++; 
     } else { 
      putchar(*str); 
     } 
     str++; 
    } 
    return count; 
} 
0

另一種方法......

#include <iostream> 
using namespace std; 

void split(char* str, char s){ 
    while(*str){ 
     if(*str==s){ 
      cout << endl; 
     }else{ 
      cout << *str; 
     } 
     str++; 
    } 
    cout << endl; 
} 

int main(){ 

    split((char*)"herp,derp",','); 
} 
1

我沒有寫了多年的代碼,但是這應該怎麼辦?

while (*str) // as long as there are more chars coming... 
{ 
    if (*str == s) printf('\n'); // if it is a separator, print newline 
    else printf('%c',*str);  // else print the char 
    str++;  // next char 
} 
+0

使用printf打印單個字符效率不高。 –

+0

是的,這不是關於高效。通常我會將結果收集到一個新的char *中並在最後打印出來。這只是爲了說明這個概念。 – Aganju

+0

當你向新手提供低效的代碼時,他們毫不猶豫地將其投入生產。後來,當他們學習如何做得更好時,一些經理會阻止他們更改工作代碼。所以最好不要建議它。 –

0

和另一個迭代

#include <iostream> 
using namespace std; 



int main() { 
    string s="1,2,3,4,5"; 
    char cl=','; 
    for(string::iterator it=s.begin();it!=s.end();++it) 
     if (*it == cl) 
     cout << endl; 
     else cout << *it; 

    return 0; 
} 

http://ideone.com/RPrls7