C language left rotation string and flipped the order of the words in the string method

  • 2020-05-09 18:55:41
  • OfStack

Left rotation string
Topic:

Defines the left rotation of a string: moves the first few characters of the string to the end of the string.

If the string abcdef   is rotated by 2   bit to get the string cdefab. Please implement the string left rotation function.

The required time for a string operation of length n   is O(n) and the auxiliary memory is O(1).

Analysis:

I see many solutions on the Internet, so I won't elaborate on them.

I'm using an asymmetric array with an exchange time complexity of O (n).

Code implementation (GCC was compiled and passed) :


#include "stdio.h"
#include "stdlib.h"
 
void reverse_str(char str[],int n,int m);
 
int main(void)
{
  char str[] = "abcdef";
  reverse_str(str,6,2);
  return 0;
}
 
//str Is an array of strings, n Is the array length, m Is the left shift number 
void reverse_str(char str[],int n,int m)
{
  int i,j;
  char tmp; 
     
  for(i=0,j=n-1;i<j;i++,j--)
  {
    tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  }
 
  for(i=0,j=n-m-1;i<j;i++,j--)
  {
    tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  }
 
  for(i=n-m,j=n-1;i<j;i++,j--)
  {
    tmp = str[i];
    str[i] = str[j];
    str[j] = tmp;
  }
 
  printf("%s\n",str);
}


Reverse the order of the words in the sentence
Reverse the order of the words in the sentence.

Topic:

Enter 1 English sentence and reverse the order of the words in the sentence, but the order of the characters inside the word remains the same.

Words in a sentence are separated by Spaces. For simplicity, punctuation marks and ordinary letters are treated like 1.

For example, input "I am a student." and output "student. a am I."

This is an easy one, just go to the code (GCC was compiled and passed)

Code implementation:


#include "stdio.h"
#include "stdlib.h"
 
void helper(char a[],int n);
 
int main(void)
{
  char str[15] = "I am a student!";
  helper(str,15);
  printf("\n");
  return 0;
}
 
void helper(char a[],int n)
{
  int e = n-1;
  int i,j,t;
   
  for(i=e;i>=0;i=j-1)
  {
    for(j=i;j>=0 && a[j]!=' ' ;--j);
    t=j+1;
    while(t<=i)
      printf("%c",a[t++]);
    if(j<0)
      return;
    else  
      printf(" ");
  }
}


Related articles: