[C/PTA - 13. Pointer 2 (in-class practice)]

1. Function questions

6-1 Use functions to partially copy strings

Insert image description here

void strmcpy(char* t, int m, char* s)
{
    
    
    int len = 0;
    char* ret = t;
    while (*ret != '\0')
    {
    
    
        ret++;
        len++;
    }

    if (m > len)
        *s = '\0';
    else
    {
    
    
        t = t + m - 1;
        while (*t != '\0')
        {
    
    
            *s = *t;
            s++;
            t++;
        }
        *s = *t;//还有\0;
    }
}

6-2 Split the integer part and decimal part of a real number

Insert image description here

void splitfloat(float x, int* intpart, float* fracpart) 
{
    
    
    int num1 = (int)x;
    *intpart = num1;
    float num2 = x-(float)num1;
    *fracpart = num2;
}

6-3 Sense of presence

Insert image description here

int frequency(char* paragraph, char* from, char* to)
{
    
    
    int x = 0;
    for (int i = 0; paragraph[i] != '\0'; i++)
    {
    
    
        if (paragraph[i] == *from)
        {
    
    
            int flag = 1;
            for (int j = 0; j < (to - from + 1); j++)
                if (paragraph[i + j] != *(from + j))
                {
    
    
                    flag = 0;
                    break;
                }
                if (flag)
                    x++;
        }
    }
    return x;
}

2. Programming questions

7-1 word reversal

Insert image description here

#include <stdio.h>
#include <string.h> 
int main()
{
    
    
	char ch[999];
	gets(ch);
	int len = strlen(ch), k = 0, i, j, flag1 = 0, flag2 = 0;
	ch[len] = ' ';
	while (k <= len)
	{
    
    
		if (ch[k] != ' ' && flag1 == 0)
		{
    
    
			i = k;
			flag1 = 1;
		}
		if (ch[k] == ' ' && flag2 == 0 && flag1 == 1)
		{
    
    
			flag2 = 1;
			j = k - 1;
		}
		if (flag1 == 1 && flag2 == 1)
		{
    
    
			flag1 = 0;
			flag2 = 0;
			for (; j >= i; j--)
				printf("%c", ch[j]);
			printf(" ");
		}
		k++;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_73900397/article/details/134742331