C语言基础编程问题,要简洁易懂的程序?

请编写函数fun,函数的功能是:在字符串中所有数字字符前加一个$字符。
例如,输入:A1B23CD45,则输出为:A$1B$2$3CD$4$5。

函数fun的原理是传字符串指针和字符串长度两个参数,用for循环遍历字符串,

当遇到数字字符时,就把数字字符和其后面的字符向后移动1个字符,

在原来数字字符的位置写一个'$',当前字符位置i加1,字符串长度n加1.

完整的C语言程序如下

#include<stdio.h>

#include<string.h>

void fun(char* s,int n){

 int i,j;

 for(i=0;s[i]!='\0';i++){

  if('0'<=s[i]&&s[i]<='9'){

   for(j=n;j>=i;j--){

    s[j+1]=s[j];

   }

   s[i]='$';

   i++;

   n++;

  }

 }

}

int main(){

 char a[80];

 scanf("%s",a);

 fun(a,strlen(a));

 printf("%s\n",a);

 return 0;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2021-04-25
函数可以这样写:
char*fun(char*c){
char b[100];
int i,j;
for(i=0,j=0;c[i];i++){
if(c[i]>='0'&&c[i]<='9')
b[j++]='$';
b[j++]=c[i];
}
b[j]=0;
return b;
}
第2个回答  2021-04-25
循环接收字符,如果字符是数字,就先输出$再输出字符,否则直接输出字符
用ctype.h中的isdight()来判断字符是不是数字

#include<stdio.h>
#include<ctype.h>
int fun()
{
char ch;
while(ch=getchar(),ch!='\n'){
if(isdight(ch))
printf("$%c",ch);
else
printf("%c",ch);
return 0;

}
int main(){
fun();
return 0;
}
第3个回答  2021-04-25

注意内循环增加一个$时,当前位置需要i++,长度n++。

#include "stdafx.h"

#include <iostream>

using namespace std;

#define N 100


void fun(char s[],int n)

{

for(int i=0;i<n;i++)

{

if (s[i] >= '0'&&s[i] <= '9')

{

for (int j = n; j >= i; j--)

s[j + 1] = s[j];

s[i] = '$';

n++;

i++;

}

}

cout << s << endl;

}

int main()

{

char s[N];

int i = 0;

cin >> s;

i = strlen(s);

fun(s,i);

system("pause");

    return 0;

}

相似回答