[英]Create a new string that contains only alphanumeric characters from the old string
仅使用stdio.h,string.h和stdlib.h库如何实现呢?
我对编程很陌生,所以请多多包涵!
char
数组。 说服自己,这是足够的空间。 不要忘记NUL。 <ctype.h>
并从该标头使用函数/宏的情况下进行此操作。 由于这是家庭作业,因此以下是口头描述:
在原始字符串上运行循环,并使用函数isalnum()
确定字符是否为字母数字。 保持另一个大小合适的char array
,每次遇到AlphaNum时,将其插入该数组。 一旦所有AlphaNum字符都已复制到第二个数组,则NULL终止它,您便拥有了字符串。
注意: isalnum()
是在ctype.h
定义的,因此,如果不允许使用它,则可能必须自己定义此函数。 那是另一回事。
您在字符串中读取的每个字符都是一个字节(您可以将其视为0到255之间的数字,这是计算机处理它们的方式),因此您只需要检查ascii表以查看字母所指的内容。
每个字母数字字符都在以下范围内:[48,58](用于数字)或[65,90](大写)或[97,122](小写)。
看这个:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 64
int isalphanum(char); /*states if a char is alphanumerical or not*/
char *getalphanum(char *, char*); /*modifies the second string to get the result*/
int main(void) {
char in[SIZE] = "Hello, W@#@#@#@#@#orl...,.,d!"; /*just a random to try out*/
char out[SIZE];
getalphanum(in, out);
printf("%s", out);
return 0;
}
int isalphanum(char a) {
if ((a >= 48) && (a <= 58))
return 1;
if ((a >= 65) && (a <= 90))
return 1;
if ((a >= 97) && (a <= 122))
return 1;
return 0;
}
char *getalphanum(char *s, char *t) {
if ((s == NULL) || (t == NULL)) /*tests if the strings are "handble"*/
return NULL;
int i = 0;
int j = 0;
char c;
while ((c = *(s + i)) != '\0') {
if (isalphanum(c)){
*(t + j) = c;
j++;
}
i++;
}
*(t + j) = '\0';
return t;
}
这段代码可以工作,非常简单,可以改进,但是您需要的一切。
最好的方法是使用ctype.h
的isalnum()
,但是现在这不是一个选择,我已经编写了一个称为isalnum_not_prefered()
的非标准/非便携式函数,它等效于ctype.h
的isalnum()
。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int isalnum_not_prefered(char s)
{
if((s >= 'A' && s <= 'Z') ||
(s >= 'a' && s <= 'z') ||
(s >= '0' && s <= '9'))
return 1;
return 0;
}
int main(void)
{
char str[] = "this!234$#&@#$^is5@#$a#@$4677~=_?}valid2234kjstring";
int len = strlen(str);
int i, j=0;
char *newstr1 = NULL;
char *newstr2 = NULL;
if ((newstr1 = (char *) malloc(sizeof(char) * len + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
for (i=0 ; i<len ; i++) {
if (isalnum(str[i])) {
newstr1[j] = str[i];
j++;
}
}
newstr1[j] = '\0';
if ((newstr2 = (char *) malloc(sizeof(char) * len + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
j=0;
for (i=0 ; i<len ; i++) {
if (isalnum_not_prefered(str[i])) {
newstr2[j] = str[i];
j++;
}
}
newstr2[j] = '\0';
printf("string : %s \n", str);
printf("result1 : %s \n", newstr1);
printf("result2 : %s \n", newstr2);
free(newstr1);
free(newstr2);
return 0;
}
注意事项:
C
字符串以\\0
终止。 因此,您正在填充的新字符串也应以\\0
结尾 malloc()
的内存必须是free()
的 malloc()
错误 ASCII
。 如果硬件支持其他字符集(例如EBCDIC
),则可能无法按预期工作。 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.