我有这个功能: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!
我有这个功能: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!
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;
}
返回类型是一个'int',所以我猜他想要从函数中打印出分割的字符串。 –
@TheObscure问题:这是可能的。我更喜欢让函数的调用者说'cout << split(...)'或其他什么。保持I/O与转换分离。 –
@JohnZwinck当功能程序员xD – Czipperz
这个怎么样?我不确定函数中的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;
}
另一种方法......
#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",',');
}
我没有写了多年的代码,但是这应该怎么办?
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
}
使用printf打印单个字符效率不高。 –
是的,这不是关于高效。通常我会将结果收集到一个新的char *中并在最后打印出来。这只是为了说明这个概念。 – Aganju
当你向新手提供低效的代码时,他们毫不犹豫地将其投入生产。后来,当他们学习如何做得更好时,一些经理会阻止他们更改工作代码。所以最好不要建议它。 –
和另一个迭代
#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;
}
考虑字符串的'linked'字符序列,并在发现','你需要移动到印刷在新行 – nullpointer
您正在寻找'join'? –
这是C还是C++?该函数需要一个'char *'而不是'字符串'。 –