自定义View系列教程00–推翻自己和过往,重学自定义View
自定义View系列教程01–常用工具介绍
自定义View系列教程02–onMeasure源码详尽分析
自定义View系列教程03–onLayout源码详尽分析
自定义View系列教程04–Draw源码分析及其实践
自定义View系列教程05–示例分析
自定义View系列教程06–详解View的Touch事件处理
自定义View系列教程07–详解ViewGroup分发Touch事件
自定义View系列教程08–滑动冲突的产生及其处理
探索Android软键盘的疑难杂症
深入探讨Android异步精髓Handler
详解Android主流框架不可或缺的基石
站在源码的肩膀上全解Scroller工作机制
Android多分辨率适配框架(1)— 核心基础
Android多分辨率适配框架(2)— 原理剖析
Android多分辨率适配框架(3)— 使用指南
讲给Android程序员看的前端系列教程(图文版)
讲给Android程序员看的前端系列教程(视频版)
Android程序员C语言自学完备手册
版权声明
- 本文原创作者:谷哥的小弟
- 作者博客地址:http://blog.csdn.net/lfdfhl
练习题
在本小结,我们做一些与字符串相关的练习。
练习1:获取字符串长度
字符串的末尾存在一个null字符,可以当读取到第一个’\0’字符时表示字符串结束。
#include <stdio.h>
#include <stdlib.h>
int getStringLen(const char s[]){
int len=0;
while(s[len]){
len++;
}
return len;
}
int main()
{
char str[100];
printf("请您输入一个字符串:");
scanf("%s",str);
int len=getStringLen(str);
printf("字符串%s的长度是%d",str,len);
return 0;
}
代码总体来说不难,重点在于while
循环,请参见代码第6—8行。我们需要注意的是:null是一个字符即‘\0’,该字符所对应的整数是0。
运行结果:
请您输入一个字符串:abc1234
字符串abc1234的长度是7
练习2:显示字符串
之前我们通常采用puts( )函数显示字符串。在此,通过putchar( )函数依次输出字符,模拟puts( )函数的功能。和刚才的练习一样,当遇到null字符即‘\0’时表示字符串的末尾。
#include <stdio.h>
#include <stdlib.h>
void showString(const char s[]){
int i=0;
while(s[i]){
putchar(s[i]);
i++;
}
}
int main()
{
char str[100];
puts("请您输入一个字符串:");
scanf("%s",str);
printf("您输入的字符串是:");
showString(str);
return 0;
}
运行结果:
请您输入一个字符串:
hello
您输入的字符串是:hello
练习3:统计字符串中各个数字出现的次数
类似的练习之前也做过,不再赘述。
#include <stdio.h>
#include <stdlib.h>
void countNumber(const char str[],int count[]){
int i=0;
while(str[i]){
if(str[i]>='0'&&str[i]<='9'){
count[str[i]-'0']++;
}
i++;
}
}
int main()
{
int i;
int count[10]={0};
char str[100];
printf("请您输入一个字符串:");
scanf("%s",str);
countNumber(str,count);
puts("统计各个数字出现次数:");
for(i=0;i<10;i++){
printf("'%d':%d\n",i,count[i]);
}
return 0;
}
运行结果:
请您输入一个字符串:12345678901234
统计各个数字出现次数:
‘0’:1
‘1’:2
‘2’:2
‘3’:2
‘4’:2
‘5’:1
‘6’:1
‘7’:1
‘8’:1
‘9’:1
练习4:英文字母大小写相互转换
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void stringToUpper(char str[]){
int i=0;
while(str[i]){
str[i]=toupper(str[i]);
i++;
}
}
void stringToLower(char str[]){
int i=0;
while(str[i]){
str[i]=tolower(str[i]);
i++;
}
}
int main()
{
char str[100];
printf("请您输入一个由小写英文字母组成的字符串:");
scanf("%s",str);
stringToUpper(str);
printf("转换成大写后的字符串:%s\n",str);
puts("再将其转换成小写");
stringToLower(str);
printf("转换成小写后的字符串:%s\n",str);
return 0;
}
在该示例中使用了系统自带函数toupper( )和toupper( )实现大小写的转换,所以需要引入ctype头文件,即代码第3行#include <ctype.h>
运行结果:
请您输入一个由小写英文字母组成的字符串:abcdef
转换成大写后的字符串:ABCDEF
再将其转换成小写
转换成小写后的字符串:abcdef