两种编程小技巧

题目:编写程序实现类似hello worldworld hello 的变化。

核心算法:先把整个语句反转,然后再逐个单词翻转

#include <stdio.h>

#include<string.h>

#define MAX 100

void reverse_word(char*src) // 函数功能翻转单词,遇空格翻转一次
{
    int len = 0;

    while(*src != '\0')
    {
        if(*src == ' ')
        {
            reverse(src - len,len);/*当src指向一个空格时,已经超出单词首地址这个单词的长度,所以要减去单词的长
            len = 0;                        
回到单词首地址*/
        }
        else
        {
            len++;
        }
        src++;
    }
    reverse(src - len,len);//最后一个单词以\n结尾,while语句对它没限制,所以最后要专门翻转最后一个单词
}

void reverse(char*str,int len) // 函数功能翻转整个句子
{
    int i;

    char temp;

    for(i = 0; i <= len / 2; i++ )
    {
        temp = *(str + i);
        *(str + i) = *(str + len - i - 1);
        *(str + len - i - 1) = temp;
    }

}


int main()
{
    char str[MAX];

    printf("Plesae input sentence:\n");
    gets(str);//用gets不用scanf,因为scanf遇到空格会停止输入

    reverse(str,strlen(str));

    reverse_word(str);

    printf("%s\n",str);
    return 0;

}


题目:编程完成如下功能,输出一串字符串中最长连续数字字符串。

如果输入123fsfs1234sfs123456,则输出123456

核心算法和上题类似,当检测到最长字符串时,要寻找到它的首地址。

#include <stdio.h>


#define MAX 100


int main()
{
    int i;
    int j;
    int k;

    int count = 0;
    int max = 0;

    char str[MAX];
    char sub[MAX];

    printf("Please input string:(0-9,a-z)\n");
    scanf("%s",str);

    for(i = 0; str[i] != '\0'; i++)
    {
        while(str[i] >= '1' && str[i] <= '9')
        {
            count++;
            i++;
        }
        if(count > max)
        {
            max = count;
            for(j = i - max,k = 0; j < i; j++) /* max是最长连续数字字符串的长度,用此时i的位置往前移动max个长度
            {                                                 就是此字符串的首地址*/
                sub[k] = str[j];
                k++;
            }
            sub[k] = '\0';
        }
        count = 0;
        k = 0;
    }
    printf("%d,%s\n",max,sub);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值