已知一个字串由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;
}