Linuxc基础 九

今天老师布置了两道题我感觉很有意思。
代码
压缩字符串代码:

int chdu(char *pStr)
{
	int len=0;
	if(pStr==NULL)
		return-1;
		while(*(pStr++))
		{
			len++;
		}
	return len;

}
void yas(char *pStr,char *pStr1)
{
	int a;
	int j=0;
	int count=0;
	int l=chdu(pStr);
	int i;
	a=pStr[0];
	for(i=0;i<l;i++)
	{
		
		if(pStr[i]==a)
		{
			count++;
		}
		else
		{
			if(count==1)
			{
				pStr1[j++]=a;	
			}
			else
			{
				pStr1[j++]=count+'0';
				pStr1[j++]=a;
			}
			count=1;
			a=pStr[i];
		}
	
	}
	if(a!=pStr[j-1])
	{
		if(count==1)
		{
			pStr1[j++]=a;	
		}
		else
		{
			pStr1[j++]=count+'0';
			pStr1[j++]=a;
		}
	
	}
	pStr[j++]='\0';

}
int main3()
{
	char str[100]="aaaabbbbcdfggg";
	char str1[200];
	int len=chdu(str);
	yas(str,str1);
	printf("%s\n",str1);

单词逆序代码:

#include <stdio.h>
#include <string.h>
void change(char *p1, char* p2)     
{
    char tmp;
    while (p1 < p2)
    {
        tmp = *p1;
        *(p1++) = *(p2);
        *(p2--) = tmp;
    }
}
void diandao(char *pStr)
{
	char* p1 = pStr;    
    char* p2 = pStr + strlen(pStr) - 1;
    char* p3 = NULL;

    change(p1, p2);      
    p2 = pStr;           

    while (*p2)          
    {
        if (' ' == *p2)  
        {
            p3 = p2 - 1;
            change(p1, p3);
            p1 = p2 + 1;  
        }
        p2++;        
    }

    if (0 == *p2)         
    {
        p3 = p2 - 1;
        change(p1, p3);
    }
    puts(pStr);   

}
int main()
{
    char str[] = {" You are  from  shanghai"};
    diandao(str);
	
	
    return 0;
}

总结
这两个程序我想了半天猜想的到之前也结合了网上的一些人的想法才写出这个程序。这两个程序也让我知道了看题目要有不同的想法只有这样才能更好写出程序。

猜你喜欢

转载自blog.csdn.net/qq_41936758/article/details/84377740