百度试题讲解:编写c语言函数去掉所有ansi编码的字母和数字

本文提供了一种使用C语言从包含GBK汉字和ANSI编码的数字字母混合字符串中删除所有ANSI编码字母和数字的方法。通过巧妙地利用步长进行操作,此方法实现了高效的原地替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

已知一个字串由GBK汉字和ansi编码的数字字母混合组成,编写c语言函数实现从中去掉所有ansi编码的字母和数字(包括大小写),要求在原字串上返回结果。
函数接口为:int filter_ansi(char* gbk_string)
注:汉字的GBK编码范围是0×8140-0xFEFE

解答:这一题其实我实现的不分gbk或者utf8编码,不过对不对,有待大家指正!
思想:在于巧用步长解决问题,因该是我能想到的运行最快的,移动次数最少的解法了~~ 

/*
 * FileName: FilterAnsi.cpp
 * Type: C++
 * Copyright: (c) 2009 Jingyi Xiao
 * Authors: Jingyi Xiao
 * Description:
 */

#include iostream
#include cstdio
#include cstring

using namespace std;

int FilterAnsi (){
  char tmp_str[] = "fkdjlsfk我防盗锁方简历57348957就分fjdk开了JKJKL方两块观看了nvu768发到vnfd感到费解观看了发到就fjdlf快了";
  int step = 0, i;
  for (i = 0; i+step < strlen(tmp_str); i++){
    while ( i + step < strlen(tmp_str) &&
    ((tmp_str[i+step] >= '0' && tmp_str[i+step] <= '9') ||
     (tmp_str[i+step] >= 'a' && tmp_str[i+step] <= 'z') ||
     (tmp_str[i+step] >= 'A' && tmp_str[i+step] <= 'Z'))
     ) {
      ++step;
    }

    if (step != 0){
      tmp_str[i] = tmp_str[i+step];
    }
  }
  tmp_str[i] = '/0';

  printf("%s", tmp_str);
  return 0;
}
This entry was posted on 星期三, 十月 7th, 2009 at 2:16 下午 and is filed under 好代码、思想、算法, 我的好codes, 百度试题解答. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “百度试题讲解:编写c语言函数去掉所有ansi编码的字母和数字”
 Ian Lee 说:
2009年10月15日 于 9:26 下午
int filter(char *str, int len)
{
int cur = 0, i;
for(i = 0; i < len; ++i)
if(!(str[i] = ’0′) &&
!(str[i] = ‘a’) &&
!(str[i] = ‘A’))
str[cur++] = str[i];
return cur;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值