编写一字符串移动函数 char*shift ( char*pstr , int n , char* mode ),该函数的功能是:(1)当 mode = R 时,将字符串 pstr 循环右移n位:(2)当 mode=L 时,将字符串 pstr 循环左移n位返回值为移位后的字符串的首地址。例如:字符串“12345678”,循环右移3位将得到“67812345”循环左移3位将得到“45678123”
1条回答 默认 最新
- 浪客 2021-06-09 01:48关注
#include <stdio.h> #include <stdlib.h> #include <string.h> char *shift(char *pstr, int n, char *mode) { int len = strlen(pstr); char *tmp = (char *)calloc(n, sizeof(char)); char *strs = (char *)calloc(len, sizeof(char)); int sublen = len - n; if (*mode == 'L') { memcpy(tmp, pstr, n); memcpy(strs, pstr + n, sublen); memcpy(strs + sublen, tmp, n); } else { memcpy(tmp, pstr + sublen, n); memcpy(strs, tmp, n); memcpy(strs + n, pstr, sublen); } free(tmp); return strs; } int main() { char *p, *str = "12345678"; p = shift(str, 3, "L"); printf("%s\n", p); free(p); p = shift(str, 3, "R"); printf("%s\n", p); free(p); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用 1