字符串右移n位

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

题目:实现字符串右移几位,即 abcd 移两位变 cdab 

思路:

  1. 申请一个与待移位同样大小的数组,用来保存移位后的字符串
  2. 通过公式计算出简化的移位数
  3. 得到某字符移位后的新位置后,就将其字符值存放到新数组的对应位置
  4. 循环第3步。直至检测到字符串结尾处
  5. 将新数组的最后一个位置赋 '\0'
  6. 输出移位后的字符串

#include <iostream>using namespace std;int main()while (1) {  int    n;     //移位数  int    index=0;    //记录待移位字符串的数组下标  int    move_num=0;   //记录简化的移位数  char   str[]="test";  //待移位字符串  int    length = strlen(str);  char  *new_str= new char[length+1];  cin >> n;  move_num = n % length;       while (*(str + index))  {   new_str[(index + move_num) % length] = *(str + index);   index++;  }  new_str[length+1] = '\0'; //别忘记加上结束符  cout << new_str << endl; } return   0;}



后续会增加不同的解法 :)



           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_43667702/article/details/84070037