[英]How to split an array of characters without using any basic function
I have this function: int split(char* str, char s)
, so how to split the str
without using strtok()
or other functions? 我有这个函数:
int split(char* str, char s)
,那么如何在不使用strtok()
或其他函数的情况下拆分str
?
Eg: str = "1,2,3,4,5", s = ','
例如:
str = "1,2,3,4,5", s = ','
After split(str, s)
, output will be: 在
split(str, s)
,输出将是:
1
2
3
4
5
Sorry guys, the int return -1 if str == NULL and return 1 if str != NULL. 抱歉,如果str == NULL,则int返回-1,如果str!= NULL,则返回1。
How about this? 这个怎么样? I'm not sure what the int return type means in the function so I made it the count of splits.
我不确定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;
}
I didn't write code for years, but that should do? 我好多年没写代码了,但是应该这样做吗?
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
}
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;
}
Another approach... 另一种方法
#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",',');
}
and another one with iterator 另一个带有迭代器
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.