C language: delete comments

Based on the insights gained after doing the questions, share with this:

Topic:
Read a line of characters from the keyboard (convention: the number of characters ≤127 bytes), and judge whether the comment is legal or not. If it is not legal, an error will be reported. If it is legal, delete the comment before outputting. A legal comment refers to the start of a comment marked with " /" and the end of a comment marked with " /", usually expressed as /* ……*/.

This sharing is divided into two steps:

  1. Code display
  2. Code sharing

1. Code display:

#include <stdio.h>
#include <string.h>

int findfirst(char str[128]);
int findlast(char str[128]);

int main(void)
{
    
    
	int first, last;
	char string[128];
	char result[128];

	printf("input a string:");
	gets(string);

	first = findfirst(string);
	last = findlast(string);

	strcpy(result, string);
	printf("%s  %s",result + first,string + last);
	if (first >= 0 && last >= 0)
	{
    
    
		strcpy(result + first, string + last);
	}


	if (first >= 0 && last >= 0 && last >= first + 4 || first == -1 && last == -1)
	{
    
    
		printf("Output:\nThe result is :\n");
		puts(result);
	}
	else
	{
    
    
		printf("Output:\ncomment is error\n");
	}
	return 0;
}

int findfirst(char str[128])
{
    
    
	int i;

	for (i = 0; str[i] != '\0'; i++)
	{
    
    
		if (str[i] == '/' && str[i + 1] == '*')
		{
    
    
			return i;
		}
	}
	return  (-1);
}

int findlast(char str[128])
{
    
    
	int i;

	for (i = 0; str[i] != '\0'; i++)
	{
    
    
		if (str[i] == '*' && str[i + 1] == '/')
		{
    
    
			return i + 2;
		}
	}
	return (-1);
}

int findfirst(char str[128]);
int findlast(char str[128]);
此处的子函的功能时是为找出'/*''*/',并对其脚标标记返回相应的脚标数值以便于主函数删除。
printf("%s  %s",result + first,string + last);

This paragraph is specially added by me, in order to be able to understand the function of the following code more clearly:

if (first >= 0 && last >= 0)
	{
    
    
		strcpy(result + first, string + last);
	}

The function of this code is to delete comments.
Then why use result + first, string + last expressions.
The use of strcpy is to copy the latter to the former. The character array name + specific number can be used to specify which one in the entire character array to start the output from. The result + first section can specify the character from-this character'/ 'Start to the following content.

The
Insert picture description here
pictures and texts are better to understand, as shown in the figure: The second paragraph in the figure is the realization of the following statement:
printf("%s %s",result + first,string + last);
How to delete it?
It depends on result + first starting from'/' to output the following strcpy copy to him to delete the latter part of string + last starting from'i'.

Guess you like

Origin blog.csdn.net/yooppa/article/details/114600681