C++字符串操作集合

mpm4 9年前發布 | 743 次閱讀 C/C++

#include <iostream>
using namespace std;
//實現一個函數求字符串的長度。
int my_length(const char s)
{
    if (s == '\0')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] != '\0'); 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 == '\0')return dist; char p = dist; while (dist != '\0')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 != '\0' && dist!=ch) { count++; dist++; } if (dist == '\0')return 0; return count+1; } int main() { cout << my_strchar("1234", '1') << endl; return 0; }</pre>

 本文由用戶 mpm4 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!