The Problem I am trying to solve is:
Consider an array of characters. start scanning each character one by one from both left and right. If both the scanned characters is an alphabet then swap them in the array.
Example:
If the array is
! w , s t u # p a b
then I will start scanning from both left and right. ie first I will scan!
andb
since both are not alphabets I will not swap. Then I will move tow
anda
, since both are alphabets I will swap them. I will continue this process till i reach the middle of the array.
我的代码:
#include <stdio.h>
#include <ctype.h>
int main() {
int p,q,len,i;
char s[100],temp;
//ask the length of string
printf("Enter the number of chars:\n");
scanf("%d",&len);
//get each char in the string and store in array s[]
printf("Enter %d chars:\n",len);
for(i=0;i<len;i++)
scanf("%c",&s[i]);
//start scanning char by char from both sides
p=0;
q=len-1;
while(p<=q)
{
// swap chars if both p and q points to a letter
if(isalpha(s[p]) && isalpha(s[q]))
{
temp=s[p];
s[p]=s[q];
s[q]=temp;
}
//increment p to move towards right
p++;
//decrement q to move towards left
q--;
}
//print all chars in the array
for(i=0;i<len;i++)
printf("%c",s[i]);
return 0;
}
我的输入:
10
!w,stu#pab
我的预期输出:
!a,sut#pwb
我得到的输出:
!w,tsu#pa
为什么我得到错误的输出?错误在哪里?
最佳答案
#include <stdio.h>
#include <ctype.h>
int main() {
int p,q,len,i;
char s[100],temp;
//ask the length of string
printf("Enter the number of chars:\n");
scanf("%d",&len);
//get each char in the string and store in array s[]
printf("Enter %d chars:\n",len);
scanf("%s",&s[i]);
//start scanning char by char from both sides
p=0;
q=len-1;
while(p<=q) {
// swap chars if both p and q points to a letter
if(isalpha(s[p]) && isalpha(s[q])) {
temp=s[p];
s[p]=s[q];
s[q]=temp;
}
//increment p to move towards right
p++;
//decrement q to move towards left
q--;
}
//print all chars in the array
for(i=0;i<len;i++)
printf("%c",s[i]);
return 0;
}
关于c - 交换数组中的元素时出现错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198377/