C++字符串操作集合
发布时间:2020-12-16 07:43:46 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #include iostreamusing namespace std;//实现一个函数求字符串的长度。int my_length(const char *s){ if (*s == ' ')return 0; else return 1+my_l
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 #include <iostream> using namespace std; //实现一个函数求字符串的长度。 int my_length(const char *s) { if (*s == ' ')return 0; else return 1+my_length(s + 1); } int main() { char *s = "123456"; cout << my_length(s) << endl; return 0; } #include <iostream> #include <assert.h> using namespace std; //实现一个求字符串的长度。 int my_length(const char *s) { if (s == NULL)return 0; int count = 0; while (s[++count] != ' '); return count; } int main() { char *s = ""; cout << my_length(s) << endl; return 0; } #include <iostream> #include <string.h> #include <assert.h> using namespace std; char* my_strcpy(char *dist,const char *scour) { assert(scour!=NULL); char *p = dist; while (*dist++ = *scour++); return p; } int main() { char *s1 = "123"; char *s2 = new char[strlen(s1)]; cout << my_strcpy(s2,s1) << endl; return 0; } #include <iostream> #include <assert.h> using namespace std; //实现库函数strcat。 char * my_strcat(char *dist,char const *scour) { assert(dist!=NULL || scour!=NULL); if (*scour == ' ')return dist; char *p = dist; while (*dist != ' ')dist++; while (*dist++ = *scour++); return p; } int main() { char *s1 = new char[10]; strcpy(s1,"123"); cout << my_strcat(s1,"456")<<endl; return 0; } #include <iostream> #include <assert.h> #include <string.h> using namespace std; //编写程序使字符串逆序。 char* my_invert(char *s) { assert(s != NULL); char *head = s; char *last = s+strlen(s)-1; char temp; while (head < last) { temp = *head; *head = *last; *last = temp; head++; last--; } return s; } int main() { char *s = new char[10]; strcpy(s,"12345"); cout << my_invert(s) << endl; return 0; } #include <iostream> #include <assert.h> using namespace std; //模拟实现strchr函数,功能:在一个字符串中查找一个字符第一次出现的位置,如果没有出现返回NULL。 int my_strchar(const char* dist,char ch) { assert(dist!=NULL); int count = 0; while (*dist != ' ' && *dist!=ch) { count++; dist++; } if (*dist == ' ')return 0; return count+1; } int main() { cout << my_strchar("1234",'1') << endl; return 0; } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |