字符和字符串处理例子
1. CharHandler.c:
/*
* charHandler.c
*
* Created on: Jul 2, 2013
* Author: wangle
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define NUMBER 11
int main(){
char c[NUMBER] = {"China No.1"};
int i;
puts(c);
printf("%c--%c\n", c[0], c[1]);
for(i=0; i<NUMBER;i++){
if(isalpha(c[i])){ //是字母吗?
if(islower(c[i])){ //是小写吗?
c[i]=toupper(c[i]); //改成大写字母
}
}
}
puts(c);
char * cPointer={"99.8% is completed!"};
char * p;
double d;
d = strtod(cPointer, &p); //把字符串中数字给d,把字符串中的首个非数字字符地址给p指针。
printf("%.2f\n", d);
printf("double is %f, the string is %s", d, p);
const char * s = {"1234567890is apple"};
long l;
l = strtol(s, &p, 10); //把字符串中数字给l,以10进制形式转换,把字符串中的首个非数字字符地址给p指针。
printf("\nlong is %ld, the string is %s", l, p);
return 0;
}
2. StringHandler.c
/*
* StringHandler.c
*
* Created on: Jul 2, 2013
* Author: wangle
*/
#include <stdio.h>
#include <string.h>
#define NUMBER 20
int main(){
const char * c = "ABCDEFG";
char a[NUMBER];
strcpy(a, c); //把c指向的字符串复制给a字符数组。
puts( a);
strncpy(a, c, 4);
puts( a);
strcat(a, c);
puts(a);
strncat(a, c, 4);
puts(a);
const char * s ="Happy New Year!";
const char * s2="Happy New Year!";
const char * s3="Happy Holidays!";
printf("%d, %d, %d\n", strcmp(s, s2), strcmp(s,s3), strcmp(s3,s2)); //字符串比较函数
printf("%d, %d, %d", strncmp(s,s2, 7), strncmp(s,s3, 7), strncmp(s2,s3,7));
}