首页 > 代码库 > C++字符串操作二

C++字符串操作二

#include <iostream>
#include <assert.h>
using namespace std;
//模拟实现strcmp函数。

bool my_strcmp(const char *str1,const char *str2) { assert(str1!=NULL && str2!=NULL); const char *p = str1; const char *q = str2; while (*p != ‘\0‘ && *q != ‘\0‘ && *p == *q) { p++; q++; } return (*p - *q)!=0; } int main() { cout << my_strcmp("liwu", "liu") << endl; return 0; } #include <iostream> #include <assert.h> using namespace std; //库函数memcopy的实现。 char *my_memcopy(char *dist, const char *src, int len) { assert(dist != NULL && src != NULL); char *p = dist; int n = len>(strlen(src)+1) ?

strlen(src)+1 : len; while (n-->0) { *dist++ = *src++; } return p; } int main() { char s1[20] = "1234"; my_memcopy(s1,"liuhuiyan",2); cout << s1 << endl; } #include <iostream> #include <assert.h> using namespace std; char* my_memove(char *dist,const char* src,int len) { assert(dist!=NULL && src!=NULL); char *p = dist; const char *q = src; int n = len>(strlen(src) + 1) ? strlen(src) + 1 : len; if (p <= q || q+n<=p) { while (n-- > 0) { *p++ = *q++; } } else { p += n-1; q += n-1; while (n-- > 0) { *p-- = *q--; } } return dist; } int main() { char s1[] = "liu hui yan"; char s2[] = "123 456"; cout << my_memove(s1, s2, 6) << endl; return 0; } #include <iostream> using namespace std; //一个字符串“student a am i”,现要求将这个字符串改动为“i am a student”。 void exchange(char *p1,char *p2) { char temp; while (p1 < p2) { temp = *p1; *p1 = *p2; *p2 = temp; p1++; p2--; } } char* my_exchange(char *src) { char *p = src; char *q = src; while (*p != ‘\0‘) { while (*p != ‘ ‘ && *p!=‘\0‘) { p++; } exchange(q,p-1); if (*p == ‘\0‘)break; p++; q = p; } exchange(src,p-1); return src; } int main() { char s[] = "student a am i"; cout << my_exchange(s) << endl; } //字符串打印数字。 #include <iostream> #include <assert.h> using namespace std; int my_int(const char *str) { assert(str!=NULL); int count = 0; while (*str != ‘\0‘) { count = (count * 10 + *str - ‘0‘); str++; } return count; } int main() { char s[] = "12345"; cout << my_int(s) << endl; return 0; }

#include <iostream>
using namespace std;
char str[] = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘ };
//输入数字1234,打印对应的字符串。

void Printf(int x) { if (x==0)return; else { Printf(x / 10); cout << str[x % 10] << endl; } } int main() { Printf(1234); return 0; }

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

C++字符串操作二