字符串遍历

字符串遍历常见有两种方法:
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);
}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值