要求实现的功能:在字符串str中找出ASCII值最大的字符,将其放在第一个位置上,并将该字符前的原字符向后顺序移动。
#include<stdio.h>
#include<ctype.h>
#include<assert.h>
void
FindMaxValue(char *pstr)
{
assert(pstr != NULL);
char max,*q=pstr; //max最大字符(选择比较),q指向遍历一次字符串后得到的最大字符的位置。
int i = 0;
max = pstr[0];
while (pstr[i]!='\0') //以非结束符为终止条件,遍历字符串。
{
if (max < pstr[i]) //max需要更新的情况。
{
max = pstr[i];
q = pstr + i; //q指向当前的最大字符。
}
++i; //循环下标+1。
}
while(q>pstr) //从最大位置开始向前逆序遍历,每次将前一个字符后移一位。
{
*q = *(q - 1);
--q;
}
pstr[0] = max; //循环结束时,0号位置空余,将最大字符max放入。
}
int
main()
{
char str[80] = {"ABCDEFGHaIJK"};
printf("the orignal string:\n");
puts(str);
FindMaxValue(str);
printf("the stirng after moving:\n");
puts(str);
}
本程序在VS2017下运行通过