2014-09-26 62 views
-2

用字符串passCode替换空格用_替换空白字符的正确方法是什么?最后它应该输入/输出:(a)(a_)。有没有办法使用isspace来做到这一点?用C语言替换空白字符

isspace(passCode[2]) == 0; 
+0

'isspace'可以*测试*为空格字符,但(在这里循环中使用时,其将是有用的)是不能够修改字符串本身。 – user2864740 2014-09-26 05:34:39

+0

请注意:'isspace()'是一个空白字符的测试,默认的C语言环境是''''''\ f'',''\ n'',''\ r' ',''\ t''或''\ v''。 – chux 2014-09-26 15:41:14

回答

0

如果是,请检查字符是否为空格,然后将其替换为_

例如:

#include <stdio.h> 
#include <ctype.h> 
int main() 
{ 
    int i=0; 
    unsigned char str[]="a "; 
    while (str[i]) 
    { 
    if (isspace(str[i])) 
     str[i]='_'; 
    i++; 
    } 
    printf("%s\n",str); 
    return 0; 
} 
+0

谢谢你做到了! – Vlad 2014-09-26 06:01:00

+0

@Vlad:Welcome :) – user1336087 2014-09-26 06:01:40

+1

此代码是危险的。您不应该直接在'char'上调用'isspace'('char'类型可能会被签名,因此会被签名扩展为不可接受的'isspace'值)。 – 6502 2014-09-26 06:22:21

0

做到这一点,最好的办法是:

#include <stdio.h> 

void replace_spaces(char *str) 
{ 
    while (*str) 
    { 
    if (*str == ' ') 
     *str = '_'; 
    str++; 
    } 
} 

int main(int ac, int av) 
{ 
    char *pass = 'pas te st'; 

    replace_spaces(pass); 
    printf("%s\n", pass); 
    return (0); 
} 

通我现在等于 'pas_te_st'。

+1

但是,如果您没有指向字符串开头的指针,现在如何打印字符串? – iveqy 2014-09-26 05:57:19

+0

注意:OP确实询问了_white_ space_与'''',尽管这种方法仍然适用。 – chux 2014-09-26 15:48:34

1

字符替换的一个简单方法就是创建一个指向字符串的指针,然后检查字符串中的每个字符的值为x,并随时随地用字符y替换它。一个例子是:

#include <stdio.h> 

int main (void) 
{ 

    char passcode[] = "a "; 
    char *ptr = passcode; 

    while (*ptr) 
    { 
     if (*ptr == ' ') 
      *ptr = '_'; 
     ptr++; 
    } 

    printf ("\n passcode: %s\n\n", passcode); 

    return 0; 
} 

输出:

$ ./bin/chrep 

passcode: a_ 
+0

注意:OP确实询问了_white_ space_与'''',尽管这种方法仍然适用。 – chux 2014-09-26 15:47:40