字符串遍历常见有两种方法:
1,while循环:
int i=0;
while(s[i])
{
处理s[i]
...
i++;
}
while( )中的循环条件s[i]可等价为s[i]!=’\0’或者s[i]!=0, 意为当遇到字符串终止符’\0’时退出循环。
2,for循环:
int l,i;
l=strlen(s);
for(i=0;i<l;++i)
{
处理s[i]
...
}
strlen( )函数用于统计字符串有效字符的大小
举例:
任意输入一个实数字符串,将其转化为实数输出。
例如:x=“123.456” out:123.456000
while循环:
#include<stdio.h>
#include<string.h> //为strlen( )提供原型
#define N 81
int main(void)
{
int y,i;
double n;
char s[N]; //定义数组
printf("请输入一个实数\n");
gets(s);
i=0;
y=0;
while(s[i]!='.') //计算出小数点之前整数部分的值
{
y=y*10+(s[i]-'0');
i++;
}
i=strlen(s)-1; //给i重新赋值
n=0.0;
while(s[i]!='.') //数组从后往前开始遍历,直到遇到小数点跳出循环
{
n=n/10+(s[i]-'0');
i--;
}
printf("%f",n/10+y);
}
for循环:
#include<stdio.h>
#include<string.h>
#define N 81
int main(void)
{
int y,i;
double n;
char s[N];
printf("请输入一个实数\n");
gets(s);
y=0;
for(i=0;s[i]!='.';++i)
{
y=y*10+(s[i]-'0');
}
i=strlen(s)-1;
n=0.0;
for(i;s[i]!='.';--i)
{
n=n/10+(s[i]-'0');
}
printf("%f",n/10+y);
}