本文介绍了c + +反向阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中,我需要:
- 在读取用户输入的字符串,并把它变成一个字符数组[完成]
- 然后该数组传递给函数[完成]
- 函数应该扭转字符的顺序[问题!]
- 然后,早在
的main()
,它会显示原始数组与新颠倒字符。
我无法创造实际执行倒车功能,因为我有一些限制:
- 我不能有任何本地数组
变数。 - 没有指针或者
我的功能仅传递原始数组,即:
void反转(字符字[])
编辑:这是我的code基至今:
void反转(字符字[]);无效的主要()
{
字符字[MAX_SIZE]; COUT<< ENDL<< 输入一个单词:
CIN>>字;
COUT<< 您输入的单词<<字LT;< ENDL; 反向(字); COUT<< 以相反的顺序的词是<<字LT;< ENDL;
}无效反向(炭myword [])
{
INT I,温度;
j--; 对于(I = 0; I&≤(焦耳/ 2);我+ +)
{
TEMP = myword [I]
myword [I] = myword [J]。
myword [J] =温度; j--;
}
}
解决方案
尽管看上去很homeworky,我建议:
void反转(字符字[])
{
INT LEN = strlen的(字);
焦温度;
的for(int i = 0; I< LEN / 2;我++)
{
TEMP =字[我]
字由[i] =字[len个-I-1];
字[len个-I-1] =温度;
}
}
,或者更好的,经典的XOR实现:
void反转(字符字[])
{
INT LEN = strlen的(字);
的for(int i = 0; I< LEN / 2;我++)
{
字由[i] ^ =字[len个-I-1];
字[LEN-I-1] ^ =字由[i];
字由[i] ^ =字[len个-I-1];
}
}
In C++, I need to:
- Read in a string from user input and place it into a char array [done]
- Then pass that array to a function [done]
- The function is supposed to reverse the order of characters [problem!]
- Then, back in the
main()
, it displays that original array with the newly reversed characters.
I'm having trouble creating the function that actually does the reversing because I have some restrictions:
- I cannot have any local arrayvariables.
- No pointers either
My function is only passing in the original array ie:
void reverse(char word[])
EDIT: Here's my code base so far:
void reverse(char word[]);
void main()
{
char word[MAX_SIZE];
cout << endl << "Enter a word : ";
cin >> word;
cout << "You entered the word " << word << endl;
reverse(word);
cout << "The word in reverse order is " << word << endl;
}
void reverse(char myword[])
{
int i, temp;
j--;
for(i=0;i<(j/2);i++)
{
temp = myword[i];
myword[i] = myword[j];
myword[j] = temp;
j--;
}
}
解决方案
Despite this looking quite homeworky, may I suggest:
void reverse(char word[])
{
int len=strlen(word);
char temp;
for (int i=0;i<len/2;i++)
{
temp=word[i];
word[i]=word[len-i-1];
word[len-i-1]=temp;
}
}
or, better yet, the classic XOR implementation:
void reverse(char word[])
{
int len=strlen(word);
for (int i=0;i<len/2;i++)
{
word[i]^=word[len-i-1];
word[len-i-1]^=word[i];
word[i]^=word[len-i-1];
}
}
这篇关于c + +反向阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!