鱼C论坛

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

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

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

  4. void double_str(char s[]) {
  5.     size_t size = strlen(s);
  6.     char *p = s + size - 1;
  7.     char *q = s + (size * 2) - 1;
  8.     q[1] = '\0';
  9.     while(p >= s) {
  10.         *q-- = *p;
  11.         *q-- = *p--;
  12.     }
  13. }

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

使用道具 举报

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

  4. void double_str(char s[]) {
  5.     size_t size = strlen(s);
  6.     char *p = s + size - 1;
  7.     char *q = s + (size * 2) - 1;
  8.     q[1] = '\0';
  9.     while(p >= s) {
  10.         *q-- = *p;
  11.         *q-- = *p--;
  12.     }
  13. }

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

使用道具 举报

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

  4. void double_str(char s[]) {
  5.     char *p = strdup(s);
  6.     char *q = s;
  7.     for(size_t i = 0; p[i]; ++i) {
  8.         *q++ = p[i];
  9.         *q++ = p[i];
  10.     }
  11.     *q = '\0';
  12.     free(p);
  13. }

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

使用道具 举报

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

  4. using std::cout, std::endl;
  5. using std::string;
  6. using std::regex, std::regex_replace;

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

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-2 15:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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