Ale*_*voi 4 c++ string reversing
我需要读取字符串(带空格)并反转它.
首先,我从控制台读取一串字符.
char array[100];
for(int i = 0; i < sizeof(array); i++)
array[i] = '0';
for(int i = 0; i < sizeof(array); i++)
cout<<array[i]<<" ";
cout<<"\n\nenter your string: ";
cin.getline(array, 100);
cout<<"\n";
for(int i = 0; i < sizeof(array); i++)
cout<<array[i]<<" ";
Run Code Online (Sandbox Code Playgroud)
然后我创建并填充索引数组.(记住空间点)
cout<<"\n\nindexes: ";
int indexes[20];
for(int i = 0; i < 20; i++)
{
indexes[i] = 0;
}
// filling the indexes array
int j = 0;
for(int i = 0; i < sizeof(array); i++)
{
if(array[i] == '0') break;
if(array[i] == ' ') indexes[j++] = i;
}
// validating indexes array
for(int i = 0; i < sizeof(indexes); i++)
{
//if(indexes[i] == 0) break;
cout<<indexes[i]<<" ";
}
Run Code Online (Sandbox Code Playgroud)
这是我(我猜不聪明)algorythm的开头.我想颠倒第一个字.
好像这个块从未执行过.为什么?
// first word
int j1 = indexes[0]-1;
for(int i = 0; i > indexes[0]; i++)
{
new_array[i] = array[j1-i];
cout<<"\naction\n";
}
Run Code Online (Sandbox Code Playgroud)
将new_array打印到控制台:
for(int x = 0; x < sizeof(new_array); x++)
{
if(new_array[x] == '0') break;
cout<<new_array[x]<<" ";
}
Run Code Online (Sandbox Code Playgroud)
结果是:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
输入你的字符串:这是我的字符串
thisismystring 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
性价比:4 7 10 17 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -858993460 -858993460 100 -85 8993460 -858993460 100 -858993460 -858993460 100 -858993460 -858993460 193628786 0 544434464 1931508077 1852404340 805314663 808464432 808464432 808464432 808464 432 808464432 808464432 808464432 808464432 808464432 808464432 808464432 808464 432 808464432 808464432 808464432 808464432 808464432 808464432 808464432 808464 432 -858993460 -742139265 6421640 18244041 1 9932784 9928256 -742139185 0 0 2129 674240 -1920 570026249 0 6422528 0 0 6421580 6421712 18223374 -759898201 0 64216 48 18244541
新阵列:
为什么索引数组在零之后包含这些数字?它的长度只有20.
为什么不打印new_array?
我知道我的解决方案非常麻烦)
你的直觉是正确的:循环没有被执行.问题在于:
for(int i = 0; i > indexes[0]; i++)
Run Code Online (Sandbox Code Playgroud)
比较应该是i < indexes[0].