简体   繁体   English

C:删除字母以外的字符的程序

[英]C: Program to delete characters other than alphabetical

so I'm trying to create a program which looks at a string defined in main, and deletes any non-alphabetical characters (excluding \\0). 所以我正在尝试创建一个查看main中定义的字符串的程序,并删除任何非字母字符(不包括\\ 0)。 So far this is my code: 到目前为止这是我的代码:

/* Write code to which considers the string currently saved
 * in the 'name' array, removes all spaces and non-alphabetical
 * chars from the string, and makes all alphabetical characters
 * lower case. */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define NAMELEN 30

int main (void) {
  char name[NAMELEN];
  strcpy(name, " William B. Gates");
    int i, length, check;

    length = strlen(name);
    for ( i = 0; i < length; i++ ) {
        check = isalpha(name[i]);
        if ( check == 0 ) {
            for ( ; i < length; i++ ) {
                name[i] = name[i+1];
            }
        }
    }
    printf("The length is %lu.\n", strlen(name));

  printf("Name after compression: %s\n", name);
  return EXIT_SUCCESS;
}

So for the test data, " William B. Gates", the output should be "WilliamBGates", unfortunately the output I'm getting is: 所以对于测试数据“William B. Gates”,输出应该是“WilliamBGates”,不幸的是我得到的输出是:

The length is 16.
Name after compression: William B. Gates

I think the space before William has been deleted, but I'm unable to tell. 我认为威廉之前的空间已被删除,但我无法分辨。 Thanks for any help! 谢谢你的帮助!

You don't need a complicated double-loop for this at all . 不都需要一个复杂的双回路这一点。 The purpose of the exercise is to maintain independent source-reader and destination-writer, only copying and advancing the latter when the former is qualified by your criteria (ie it answers true to isalpha ). 练习的目的是保持独立的源 - 读者和目的地 - 作者,只有当前者符合您的标准时才复制和推进后者(即它对isalpha回答是正确的)。

in other words: 换一种说法:

#include <stdio.h>
#include <ctype.h>

int main (void)
{
    char name[] = " William B. Gates";
    char *dst = name, *src;

    for (src = name; *src; ++src)
    {
        if (isalpha((unsigned char)*src))
            *dst++ = *src;
    }
    *dst = 0; // terminate the string

    printf("result: %s\n", name);
}

Output 产量

result: WilliamBGates

I leave translating to lower case during the copy-step as an exercise for you. 我会在复制步骤中将翻译成小写作为练习。 (from your in-code comment: "makes all alphabetical characters lower case"). (来自您的代码内注释:“使所有字母字符小写”)。

This inner loop is wrong 这个内循环是错误的

    if ( check == 0 ) {
        for ( ; i < length; i++ ) {
            name[i] = name[i+1];
        }

It copies the string in itself excluding the first character and after that your program does nothing because i is already equal to length. 它复制除了第一个字符之外的字符串,然后你的程序什么也不做,因为我已经等于长度了。

So the program only removes one non-alpha character from the string. 所以程序只从字符串中删除一个非alpha字符。

When you are going to traverse a string sequantially then there is no need to calculate its length. 当你要在序列上遍历一个字符串时,就不需要计算它的长度了。 The program can be written simpler or at least you may use the approach that is demonstrated below. 程序可以写得更简单,或者至少可以使用下面演示的方法。 For example 例如

#include <stdio.h>
#include <ctype.h>

int main( void )
{
    char name[] = " William B. Gates";

    printf( "\"%s\"\n", name );

    size_t j = 0;
    for ( size_t i = 0; name[i] != '\0'; i++ )
    {
        if ( isalpha( ( unsigned char )name[i] ) )
        {
            if ( j != i ) name[j] = name[i];
            ++j;
        }
    }
    name[j] = '\0';

    printf( "\"%s\"\n", name );

}   

The program output is 程序输出是

" William B. Gates"
"WilliamBGates"

The posted code tries to hard. 发布的代码试图努力。

The following code 以下代码

  • compiles cleanly 干净利落地编译
  • contains useful comments to clarify what is being done 包含有用的注释,以阐明正在做什么
  • performs correctly 正确执行
  • uses meaningful variable names 使用有意义的变量名

notice the simplicity of the code, and all performed in only one pass through the name[] array. 注意代码的简单性,并且只在一次通过name []数组中执行。

#include <stdio.h>
#include <ctype.h>

int main( void )
{
    char name[] = " William B. Gates";

    printf( "\"%s\"\n", name );

    size_t src  = 0;
    size_t dest = 0;
    for( ; name[src]; src++)  // will exit loop when string terminator '\0' encountered
    {
        if( isalpha(name[src]) )
        { // then current char is: a...zA...Z
            name[dest] = tolower(name[src]); // force lower case
            dest++; // update where to save next character
        }
    }

    name[dest] = '\0'; // terminate the modified string

    printf( "\"%s\"\n", name );

    return 0;
} // end function: main

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

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