字符串循环左移

输入一个字符串和一个非负整数N,要求将字符串循环左移N次。

输入格式:

输入在第1行中给出一个不超过100个字符长度的、以回车结束的非空字符串;第2行给出非负整数N。

输出格式:

在一行中输出循环左移N次后的字符串。

输入样例:
Hello World!
2
输出样例:
llo World!He

#include<stdio.h>
#include<string.h>

int main(){ char s[101],s2[101];
  int n;
  gets(s);
  char *p=s;
  scanf("%d",&n);
  n= n % strlen(s);//左移长度判断
  p=p+n;
  strcpy(s2,p);//标志右边的复制给s2
  //s2[n]='';
  *p='';//s修改成标志左边的字符串
  //strcpy(s,p);
  strcat(s2,s);//连接操作完成左移;
  puts(s2);
  return 0;
}

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. int main(void){
  5.     const int length_of_array = 101;                //定义数组长度 
  6.     char sentence[length_of_array];
  7.     char *temporary = (char*)malloc(sizeof(char)*length_of_array);   //临时内存空间 
  8.     int shift;                         //偏移量     
  9.     gets(sentence);
  10.     scanf("%d",&shift); 
  11.     int length_of_sentence = strlen(sentence);           //取得输入数据的长度    
  12.     if ( shift > length_of_sentence){                    //处理偏移量大于数据长度的情况 
  13.         shift = shift % length_of_sentence;
  14.     } 
  15.    
  16.     char *located_address = sentence + shift;  //该地址是“相对原始地址来说偏移shift后的地址 ”  
  17.       
  18.     strcpy(temporary,located_address);      //将偏移后地址的全部内容复制到临时容器中 
  19.     *located_address = '';          //将偏移后的地址对应的数据修改为''供下面使用 
  20.     strcat(temporary,sentence);         //原始地址的数据内容直接追加到临时空间 
  21.         printf("%s",temporary); free(temporary);        
  22.     return 0;
  23. }
原文地址:https://www.cnblogs.com/emochuanshuo/p/3918649.html