小米笔试题第1题

将字符串

 "a"

"my.ABC"

"simple.HelloService"

"MY.ASTParser123"

转换成宏:

_A_

_MY_ABC_

_SIMPLE_HELLO_SERVICE_

_MY_AST_PARSER_123_

代码如下:

#include 
#include 
#include 
using namespace std;

void StringConversion(const char *str)
{
	if(str == NULL)
		return;

	int len = strlen(str);
	char tar[1024];
	memset(tar, '\0', sizeof(tar));

	tar[0] = '_';
	int count = 1;

	for (int i = 0; str[i] != '\0' && i < len;)
	{
		if(str[i] == '.')
		{
			tar[count++] = '_';
			i++;
		}

		for(int k = i; isalpha(str[i]) && islower(str[i]); i++)
		{
			tar[count++] = str[i] - 32;
		}

		for (int k = i; isalpha(str[i]) && isupper(str[i]); i++)
		{
			if(k == i && tar[count-1] != '_')
				tar[count++] = '_';

			if(islower(str[i+1]) && tar[count-1] != '_')
				tar[count++] = '_';

			tar[count++] = str[i];
		}

		for(int k = i; isdigit(str[i]); i++)
		{
			if(k == i && tar[count-1] != '_')
				tar[count++] = '_';
			tar[count++] = str[i];
			
			if(isalpha(str[i+1]))
				tar[count++] = '_';
		}
	}

	tar[count++] = '_';
	tar[count] = '\0';

	cout << tar << endl;
}

int main1(int argc, char const *argv[]) //实验用例
{
	char s1[] = "a";
	char s2[] = "my.ABC";
	char s3[] = "simple.HelloService";
	char s4[] = "MY.ASTParser123";
	char s5[] = "iEIANo.ioSABt.123IEreamABbT.i1d23aTc.456";
	char *str[] = {s1, s2, s3, s4, s5};

	for (int i = 0; i < 5; ++i)
	{
		StringConversion(str[i]);
	}

	return 0;
}

int main(int argc, char const *argv[]) //正式main函数
{
	char str[50] = "\0";

	while(scanf("%s", str))
	{
		StringConversion(str);
		memset(str, '\0', sizeof(str));
	}

	return 0;
}


你可能感兴趣的:(笔试题)