本文介绍了如何将数组(或c串)的元素向左移动给定数字的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在写一个函数,将我的c字符串的字符向左移动给定数量的字符。目前的功能将移动字符左,但我失去了一个。我知道这是一个索引问题与我的for循环,但我不能固定下来。I am writing a function to shift the characters of my c-string left by a given number of characters. Currently the function will shift the characters left but I am losing one. I know it is some sort of indexing issue with my for loop, but I can't pin it down.编辑:按shift left我的意思是: By shift left I mean:给定a,b,c,d 的起始c字符串如果向左移一个索引,这个数组将等于b,c,d,a 如果向左移两个索引,这个相同的c字符串将等于c,d,a,b Given a starting c-string of a, b, c, d if shifted left one index this same array would equal b, c, d, aif shifted left two indexes this same c-string would equal c, d, a, b这里是我的代码到目前为止:Here is my code so far:#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;}这里是我的工作功能,将每个元素向右移动,要做的是逆向这个循环,并移动元素离开,如下所示:Here is my working function that shifts each element to the right, all I need to do is reverse this loop, and move the elements left, as in this way: <----//function bloackvoid 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; } }} 推荐答案有了一些风扇,我能够让它工作。这是我的功能函数:)With a little fanangling, I was able to get it to work. Here is my functioning function :)问题是,我需要分配元素i到i + shiftBy,并且只重复循环,而i The issue was that I needed to assign element i to i+shiftBy, and only repeat the loop while i < size-shiftBy.//function bloackvoid 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) } }} 这篇关于如何将数组(或c串)的元素向左移动给定数字的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 18:12