如何在不使用任何基本功能的情况下拆分字符数组

时间:2015-12-22 03:36:39

标签: c++

我有这个功能:int split(char* str, char s),那么如何在不使用str或其他功能的情况下拆分strtok()

例如:str = "1,2,3,4,5", s = ','

split(str, s)之后,输出将为:

1
2
3
4
5

很抱歉,如果str == NULL,int返回-1,如果str!= NULL则返回1。

5 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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
}

答案 2 :(得分: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;
}

答案 3 :(得分: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",',');
}

答案 4 :(得分: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

相关问题