如何将数组(或c字符串)中的元素左移给定数量的索引

how to shift elements of array (or c-string) left by a given number indexes

本文关键字:左移 元素 索引 数组 字符串      更新时间:2023-10-16

我正在编写一个函数,将c字符串的字符向左移动给定数量的字符。目前,该功能将向左移动字符,但我正在失去一个。我知道我的for循环存在某种索引问题,但我无法确定。

编辑:左移我的意思是:

给定a,b,c,d的起始c字符串如果左移一个索引,则相同的数组将等于b、c、d、a如果向左移动两个索引,则相同的c字符串将等于c,d,a,b

这是我到目前为止的代码:

#include <iostream>
using namespace std;
void shiftleft (char myarray[], int size, int shiftBy)
{
char temp;
for (int i=size-1; i > 0; i--)
{
    temp = myarray[size+shiftBy];
    myarray[size+shiftBy] = myarray[i];
    myarray[i] = temp;
}

}
int main() {
    char myarray[20] = "test";
    int size = 4;
    shiftleft (myarray, size, 1);
    for(int i = 0; i < size+1; i++){
    cout << myarray[i];
    }

    return 0;
}

这是我的工作函数,它将每个元素向右移动,我所需要做的就是反转这个循环,并将元素向左移动,如下所示:<----

//function bloack
void shiftright (char myarray[], int size, int shiftBy)
{
    if(shiftBy > size){
        shiftBy = shiftBy - size;
    }
    if(size == 1){
        //do nothing
    }
    else{
        char temp;
        //for loop to print the array with indexes moved up (to the right) --> by 2
        for (int i=0; i < size; i++)
        {
            temp = myarray[size-shiftBy];
            myarray[size-shiftBy] = myarray[i];
            myarray[i] = temp;
        }
    }
}

如果您想将字符串向左移动而不旋转,可以使用以下代码:

void shiftLeft (char *string,int shiftLength)
{
int i,size=strlen(string);
if(shiftLength >= size){
    memset(string,'',size);
    return;
}
for (i=0; i < size-shiftLength; i++){
    string[i] = string[i + shiftLength];
    string[i + shiftLength] = '';
}
}

经过一番努力,我就可以让它工作了。这是我的功能:)

问题是我需要将元素I分配给I+shiftBy,并且只在I<size shiftBy。

//function bloack
void shiftLeft (char myarray[], int size, int shiftBy)
{
    if(shiftBy > size){
        shiftBy = shiftBy - size;
    }
    if(size == 1){
        //do nothing
    }
    else{
        char temp;
        //for loop to print the array with indexes moved up (to the left) <-- by 2
        for (int i=0; i < size-shiftBy; i++)
        {//EXAMPLE shift by 3  for a c-string of 5
            temp = myarray[i];//temp = myarray[0]
            myarray[i] = myarray[i + shiftBy];//myarray[0] == myarray[2]
            myarray[i + shiftBy] = temp;//myarray[2] = temp(value previously at index i)
        }
    }
}

//假设j是的移位长度

char* name = strdup("Hello");
char* str_ptr = (char*) malloc(sizeof(char));  
strcpy(str_ptr, name);
int j = 3 // len of shift
for(int i = 0; i < strlen(str_ptr); i++){
  printf("%c", str_ptr[(i+j)%strlen(str_ptr)]);
}