[英]Space remove from String
#include<stdio.h>
#include<string.h>
int main(){
char array[]="Arijit Saha Student";
spaceremover(array);
getch();
return 1;
}
int spaceremover(char a[]){
int i;
// printf("L=%d",strlen(a));
char final[strlen(a)+1];
int count=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]!=' ')
final[count]=a[i];
count++;
}
final[count]='\0';
int j=0;
for(j=0;j<strlen(final);j++)
printf("%c",final[j]);
// printf("\n%s",final);
return 1;
}
With this example code the output is Arijit.Saha
, but my desired output is ArijitSahaStudent
. 在此示例代码中,输出为Arijit.Saha
,但我想要的输出为ArijitSahaStudent
。 Why am I getting the wrong output? 为什么我得到错误的输出? Where the . 哪里了。 is coming from? 是从哪里来的?
The error is here: 错误在这里:
if(a[i]!=' ')
final[count]=a[i];
count++;
The count++
should be included in the if
, so: count++
应该包含在if
,因此:
if(a[i]!=' ') {
final[count]=a[i];
count++;
}
Note: It is considered good programming practice to always use curly braces after if
statements. 注意:在if
语句之后始终使用花括号被认为是一种良好的编程习惯。
In the for loop you increase count even if a[i] == ' '
. 在for循环中,即使a[i] == ' '
您也要增加计数。
So when a[i] == ' '
you only increase count but doesn't set final[count]
to anything. 因此,当a[i] == ' '
您只会增加计数,而没有将final[count]
设置为任何值。
I assume you ment to write: 我想你要写:
if (a[i] != ' ')
{
final[count] = a[i];
count++;
}
You are not incrementing count correctly. 您没有正确增加计数。 It needs to be in the if loop. 它必须在if循环中。 This might be easier for you to see if things are indented correctly. 这可能使您更容易查看事物是否正确缩进。
#include<stdio.h>
#include<string.h>
int main(){
char array[]="Arijit Saha Student";
spaceremover(array);
return 1;
}
int spaceremover(char a[]){
int i;
// printf("L=%d",strlen(a));
char final[strlen(a)+1];
int count=0;
for(i=0;i<strlen(a);i++)
{
if(a[i]!=' ')
final[count++]=a[i];
}
final[count++]='\0';
int j=0;
for(j=0;j<strlen(final);j++)
printf("%c",final[j]);
// printf("\n%s",final);
return 1;
}
In the loop, the count should increase if a[i] not equal to space 在循环中,如果a [i]不等于空格,则计数应增加
if(a[i]!=' ') final[count]=a[i]; count++;
if(a[i]!=' ')
final[count++]=a[i];
//count++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.