3

大家好,我在用 C 格式化字符串时遇到了一个小问题。

char buffer[1000];

我的缓冲区的读数为"♀ ‼☻☺ ☻ ]\[MY-TEXT"// 缩短

如您所见,它包含非法字符,因此我无法sscanf在其上使用。我需要删除所有非法字符并保留所有数字、字母和-符号。

这可能吗?

这是我的新代码

#include <stdio.h> 
#include <string.h> 
#include <windows.h> 

int main () 
{ 

    char buffer[1000]="♀ ‼☻☺ ☻ ]\[MY-TEXT";

char buffer2[1000]; 
char *in; 
char *out = buffer2; 

for (in=buffer; *in; in++) 
   if (isalnum((unsigned char)*in) || *in == '-') 
       *out++ = *in; 

printf("Output",buffer2);


 system("pause");
    return 0; 
} 
4

3 回答 3

4

将数据从现有字符串复制到新字符串通常最简单,只需保留您想要的字符串即可:

char buffer2[1000];
char *in;
char *out = buffer2;

for (in=buffer; *in; in++)
   if (isalnum((unsigned char)*in) || *in == '-')
       *out++ = *in;
于 2012-07-20T18:33:42.113 回答
2

循环遍历数组,并仅将您接受的那些字符复制到另一个数组中,使用isalnum并测试-

char tmpBuffer[1000];
for (i = 0, j = 0; i < 1000; i++)
{
    if (isalnum(buffer[i]) || (buffer[i] == '-'))
           tmpBuffer[j++] = buffer[i];
}
于 2012-07-20T18:33:28.680 回答
0

修改函数is_valid(),使其为您想要的字符返回一个真值(非零),并为您不想要的字符返回一个假值(零)。我让它检查字符是空格还是可打印的 ASCII。

#include <stdio.h>

int
is_valid(char ch)
{
    if (' ' <= ch && ch <= '~')
        return 1;
    else
        return 0;
}

void
copy_only_valid(char *out, unsigned int max_out, char const *in)
{
    if (!out || !max_out || !in)
        return;

    for (;;)
    {
        if (*in == '\0' || max_out == 1)
        {
            // When we reach the terminating NUL byte in the input string,
            // or there is only one char left in out buffer, put a NUL byte
            // and return.
            *out = '\0';
            return;
        }
        if (is_valid(*in))
        {
            *out++ = *in++;
            --max_out;
        }
        else
            ++in;
    }
}

int
main()
{
    char const *bad = "\b\nfoo\003\005bar\f\tbaz";
    char buf[128];

    copy_only_valid(buf, sizeof(buf), bad);
    puts(buf);
}
于 2012-07-20T18:47:35.017 回答