如何将数组(或c字符串)中的元素左移给定数量的索引
how to shift elements of array (or c-string) left by a given number indexes
我正在编写一个函数,将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)]);
}
相关文章:
- 使用boost::multiprecision cpp_int左移时出现超时错误
- 警告:左移计数 >= 在 C++ 中将字节流读取为双精度变量时的类型宽度
- 左移<<如何在不同的功能中给出不同的结果?
- 使用 AVX2 指令左移 128 位数字
- <<(按位左移)在 Swift 中的数组上做什么?
- 带有左移操作员C 的意外输出
- 编译器将输出的流运算符<<解释为用于按位左移的二进制运算符<<
- 左移负整数为零是否有意义?
- 在 VS 移位中,UINT64 上的左移(64 >移位> 32)位仅 32 位
- C++20 是否为"overflow"的有符号整数很好地定义了左移?
- C++左移操作
- 为什么编译器左移 0
- 如何在位明智的操作中选择正确的左移
- 为什么很多人使用左移<<而不是乘法
- 左移 0 有什么意义
- 虽然左移运算符 (<<) 在 std::cout 之前使用,但它有什么用?
- 左移<<有些意外的行为
- 使用左移运算符将 F 转换为 FF
- 右移速度与左移相同的速度测试位
- 如何将数组(或c字符串)中的元素左移给定数量的索引