鱼C论坛

 找回密码
 立即注册
查看: 2615|回复: 3

[已解决]需要用到哪个函数

[复制链接]
发表于 2022-11-11 09:16:16 | 显示全部楼层 |阅读模式
10鱼币
编写函数void doublestr(char s[]),接收一个字符串,进行字符数组变换,要求把字符串的每个字符都重复一次。例如接收字符出 abcde,字符数组变换结果aabbccddee。
最佳答案
2022-11-11 09:16:17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void double_str(char s[]) {
    size_t size = strlen(s);
    char *p = s + size - 1;
    char *q = s + (size * 2) - 1;
    q[1] = '\0';
    while(p >= s) {
        *q-- = *p;
        *q-- = *p--;
    }
}

int main(void) {
    char buff[20];
    strcpy(buff, "hello");
    double_str(buff);
    puts(buff);
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-11-11 09:16:17 | 显示全部楼层    本楼为最佳答案   
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void double_str(char s[]) {
    size_t size = strlen(s);
    char *p = s + size - 1;
    char *q = s + (size * 2) - 1;
    q[1] = '\0';
    while(p >= s) {
        *q-- = *p;
        *q-- = *p--;
    }
}

int main(void) {
    char buff[20];
    strcpy(buff, "hello");
    double_str(buff);
    puts(buff);
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-11-11 09:31:58 | 显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void double_str(char s[]) {
    char *p = strdup(s);
    char *q = s;
    for(size_t i = 0; p[i]; ++i) {
        *q++ = p[i];
        *q++ = p[i];
    }
    *q = '\0';
    free(p);
}

int main(void) {
    char buff[20];
    strcpy(buff, "hello");
    double_str(buff);
    puts(buff);
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-11-11 09:54:25 | 显示全部楼层
C里面我没有好用的正则表达式库
用C++的了
#include <iostream>
#include <string>
#include <regex>

using std::cout, std::endl;
using std::string;
using std::regex, std::regex_replace;

const string double_str(const string &s) {
    regex pattern(R"(.)");
    return regex_replace(s, pattern, R"($0$0)");
}

int main(void) {
    string s = "hello";
    cout << double_str(s) << endl;
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-20 16:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表