|
发表于 2019-9-27 17:14:15
|
显示全部楼层
本帖最后由 muye12921 于 2019-9-27 17:18 编辑
- int my_strlen(const char* str)
- {
- int i;
- for (i = 0;; i++)
- if (str[i] == '\0') break;
- return i;
- }
- char* my_strcat(char* destination, const char* source, int buffer)
- {
- int des_len = my_strlen(destination);
- int source_len = my_strlen(source);
- if (buffer <= des_len + source_len + 1) {
- if (buffer <= des_len + 1) {
- return destination;
- }
- else {
- int i, j;
- for (i = des_len, j = 0; i < buffer - 1; i++, j++)
- {
- destination[i] = source[j];
- }
- destination[i] = '\0';
- }
- }
- else {
- int i, j;
- for (i = des_len, j = 0; i < des_len + source_len; i++, j++)
- {
- destination[i] = source[j];
- }
- destination[i] = '\0';
- }
- return destination;
- }
复制代码
测试函数
- void testMyStrCat()
- {
- char a[50] = "hello ";
- char b[] = " what is your name?";
- cout << "length a: " << my_strlen(a) << endl;
- cout << "length b: " << my_strlen(b) << endl;
- cout << "sizeof(a): " << sizeof(a) << endl;
- my_strcat(a, b, sizeof(a));
- cout << "连接后的字符串:" << a << " 长度为:" << my_strlen(a) << endl;
- }
复制代码
大概实现了一个相对安全的strcat版本和一个求字符串长度的方法my_strlen,但中文字符连接上还有问题。。。有空再改改 |
|