简体   繁体   English

如何检查我的char字符串空格?

[英]How to check my char string for spaces?

I want to take a string and output it without spaces. 我想取一个字符串并输出它没有空格。 I wrote the code below but my if statement doesn't seem to detect the spaces in the char string or I am not doing this right. 我编写了下面的代码,但我的if语句似乎没有检测到char字符串中的空格,或者我没有这样做。

I assume that my problem is in my if statement but I don't know how to fix it. 我认为我的问题出在我的if语句中,但我不知道如何修复它。

int main (void)
{
  char s[50];

  printf("Enter string:");
  fgets(s,50,stdin);

  for( int i = 0; i < strlen(s); i++ ){
    if( &s[i] != " " ){
     printf("%c\n", s[i]);
    }
  }

  return 0;
}

Output: 输出:

Enter string:xales was here
x
a
l
e
s

w
a
s

h
e
r
e

The important thing to note is that a double-quoted character is actually a string, not a char type. 需要注意的重要一点是双引号字符实际上是字符串,而不是字符类型。 This value holds a memory address to a place in your program's memory (not a value on the stack) that happens to be 2 bytes long (one for the space, one for \\0 ). 该值将内存地址保存到程序内存中的某个位置(不是堆栈中的值),该位置恰好是2个字节长(一个用于空间,一个用于\\0 )。 So that's thing #1: change " to ' and you'll have a single char, on the stack, to compare by value. 所以这就是#1:改变" to ' ,你将在堆栈中有一个char来按值进行比较。

Thing number two is that by using the & symbol there, you are trying to compare to the address of the i th index in your string, instead of the value there. 第二个是通过在那里使用&符号,你试图比较字符串中第i个索引的地址,而不是那里的值。 Just remove the & . 只需删除&

Yes, you are right. 是的,你是对的。 Your if condition is always going to be true, hence, you will be end up printing the entire string as it is. 你的if条件总是如此,因此,你将最终按原样打印整个字符串。
Your if condition: if( &s[i] != ' ' ) print s [i]; 你的if条件: if( &s[i] != ' ' ) print s [i];

Here "&" represents address. 这里“&”代表地址。 So in your if block what you are checking is: 所以在你的if块你正在检查的是:

  ` if(addressof( s[i] != ' ') print s[i]; `

Now address is never space, hence your if block will always be true. 现在地址永远不是空格,因此你的if块永远都是真的。 But as you want to check for s to be printed without spaces check for values: if( s[i] != ' ' ) print s [i]; 但是,当你想要检查没有空格的s打印时,检查值: if( s[i] != ' ' ) print s [i];

Also, as you are comparing charecter wise, you should understand that, " " is for string and for characters you should use single quotes ' '. 此外,当你比较charecter时,你应该明白,“”用于字符串,对于字符,你应该使用单引号''。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM