//字符串从两端移动,向两端汇聚
#include<stdio.h>
#include <string.h>
#include <math.h>
#include <windows.h>
int main(){
//初始化的字符串,二者的长度(所占的位必须相同)
char arr1[] = "welcome to you";
char arr2[] = "**************";
//左右两端字符的范围[left,right]
int left = 0;
//字符串长度拿strlen 函数来进行判定
int right = strlen(arr1) - 1;
//满足该条件时,依次按照角标进行相应赋值转换
while (left <= right){
//Sleep()在windows.h中。单位是毫秒
Sleep(1000);
//system("cls");//实现清除屏幕
//左右赋值的过程
arr2[left] = arr1[left];
arr2[right] = arr1[right];
left++;
right--;
printf("%s\n", arr2);
}
system("pause");
return 0;
}
难点 :该题需要会判定长度的范围:[left right]左边left初始从0开始变化依次增加,right是从最高位依次递减right=strlen()-1;(借助strlen 函数)
运行结果:
要注意strlen函数的用法
1.确定字符串的长度 遇到 \0则停止计算
举例:
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char arr[] = "abcdef"; //以 \0 结束
strlen函数遇到\0就停止不再计算其长度
printf("%d\n",strlen(arr));
system("pause");
return 0;
}
运行结果: