【2017年整理】字符串循环右移n位

上传人:豆浆 文档编号:1070567 上传时间:2017-05-27 格式:DOC 页数:5 大小:32.50KB
返回 下载 相关 举报
【2017年整理】字符串循环右移n位_第1页
第1页 / 共5页
【2017年整理】字符串循环右移n位_第2页
第2页 / 共5页
【2017年整理】字符串循环右移n位_第3页
第3页 / 共5页
【2017年整理】字符串循环右移n位_第4页
第4页 / 共5页
【2017年整理】字符串循环右移n位_第5页
第5页 / 共5页
亲,该文档总共5页,全部预览完了,如果喜欢就下载吧!
资源描述

《【2017年整理】字符串循环右移n位》由会员分享,可在线阅读,更多相关《【2017年整理】字符串循环右移n位(5页珍藏版)》请在金锄头文库上搜索。

1、c 语言 输入一个字符串 循环右移 n 个 得到一个新的字符串2011-5-15 22:25提问者:匿名|浏览次数:880次老师布置了一道题编写一个函数,作用是把一个 char 组成的字符串循环右移 n 个。比如原来是 “ hellow“如果 n=2 ,移位后应该是 “owhell”我偷了小懒用下面的方法实现了 但是当 n =4 程序的 h 就输入不出来了 那为高手帮忙解释下 谢谢了#include #include void LoopMove(char *s,int n)char *s1;int t1=strlen(s);int t =strlen(s)-n;char s2 =0;s1=s+

2、t;printf(%dn,t);strcpy(s2,s1);strncpy(s2+n,s,t);strcpy(s,s2);int main()int n=4;char s =hello;char *p= NULL;LoopMove(s,n);printf(%sn,s);谢谢!我来帮他解答2011-5-15 22:50满意回答有问题找代码:char s2 =0;这里相当于 s2是1 个字符的数组。当对它做类似 strcpy(s2,s1);的操作时,只要 s1的长度(这里是 n)大于1 ,就会出现数组访问越界。对于像数组访问越界这种错误会引发的结果是不确定性,有可能程序正常运行,也可能会崩溃,取决

3、于越界之后访问到的内存地址的相关属性。将 s2改一个动态数组,程序就能正常运行。代码如下:#include #include #include void LoopMove(char *s,int n)char *s1;int t1=strlen(s);int t =strlen(s)-n;char* s2 = (char*)malloc(t1 + 1) * sizeof(char); /分配 t1+1个字符的空间,之所以加1是因为 C 中字符串默认以0 结尾,strlen 的结果是没包含这个0 的。memset(s2, 0, t1 + 1); / 清空 s2的内容s1=s+t;printf(%

4、dn,t);strcpy(s2,s1);strncpy(s2+n,s,t);strcpy(s,s2);free(s2); / 释放资源int main()int n=4;char s =hello;char *p= NULL;LoopMove(s,n); printf(%sn,s);在一次面试题中曾遇到过一个题目是使字符串循环移动指定的位数!下面和大家讨论几点有关的算法!#include#include#includevoid strRightMove(char*a,int bit)int len= strlen(*a);if(bit%= len)char *str=(char*)malloc

5、(len+ 1);strncpy(str,(*a+ len- bit), bit);strbit= 0;strncat(str,*a,len-bit);*a= str;int main()char *a= 1234567890;strRightMove(&a,5);puts(a);return 0;当然还有其他方法#includestring.h#includestdlib.hvoid right_shift(char *dest,int shift)char *temp= NULL;int len= 0;int actual= 0;int i= 0;int sub= 0;if(shift 0

6、)printf(Error numbern);return;if(dest= NULL| *dest= 0)printf(Error:Null stringn);len= strlen(dest);actual= shift% len;if(actual= 0)return;temp= (char*)malloc(sizeof(char)* (len+ 1);for(i= actual; i len;+i)tempi= desti- actual;sub= len- actual;for(i= 0; i actual;+i)tempi= destsub+ i;templen= 0;strcpy(dest,temp);free(temp);int main(void)char str10= abcdefg;int n= 0;while(n!=1)printf(Input the number :n);scanf(%d,&n);right_shift(str, n);printf(%sn,str);return 1;还有其他方法,可以这样考虑,在这个字符串中找到一个分割点,既然是循环右移,只需要将分割点后面的整体移到前面就可以了!

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 行业资料 > 其它行业文档

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号