标签:左旋字符串
问题:
3.实现一个函数,可以左旋字符串中的k个字符。
AABCD左旋一个字符得到ABCDA
AABCD左旋两个字符得到BCDAA
#include<stdio.h> #include<assert.h> #include<string.h> void reserve(char* str, int len) { assert(str); char* start = str; char* end = str + len - 1; while (start < end) { char tmp = *start; *start = *end; *end = tmp; start++; end--; } } void reserve1(char* str, int len, int k) { reserve(str, len);//dcbaa assert(str); char* start = str ; if (k < len) { char* end = str + len - 1 - k; while (start < end) { char tmp = *start; *start = *end; *end = tmp; start++; end--; } } else { printf("输入的字符串个数太大\n"); } } void reserve2(char* str, int len,int s) { assert(str); reserve1(str, len, s);//cdbaa char* start = str+len-s; char* end = str + len - 1; while (start < end) { char tmp = *start; *start = *end; *end = tmp; start++; end--; } } int main(void) { char str[] = "aabcd"; int len = strlen(str); int s; printf("请输入要旋转的字符串个数\n"); scanf_s("%d", &s); reserve2(str, len, s); printf("%s", str); }
本文出自 “程序的灵魂” 博客,谢绝转载!
标签:左旋字符串
原文地址:http://9195095.blog.51cto.com/9185095/1709671