C++编程——找出字符串中同时包含大写和小写的字母

题目:找出字符串中同时包含大写和小写的字母,并返回字母的个数:

eg:   (1)"I Love you"     : return 0;

        (2)"I Like you"      :return  1;   (Ii)

        (3)"I Like you,Lily" :return 2;   (IiLl)

        (4)"AaBBBBbCcdddde"   :return 3;  (AaBbCc)

解法一:当你需要快速的获取对应key的value的时候,就可以使用map了。这里利用map中键的唯一性和和大、小写的映射关系来解题。

int count_of_letter_both_upper_lower_case(const char *str)
{
	int a = 0;
	int i = 0;
	map map_chars_find;
	map::iterator it,pend,index;
	while (str[i] != '\0')
	{
		if ('A' <= str[i] && str[i] <= 'Z' || 'a' <= str[i] && str[i] <= 'z')
		{
			map_chars_find.insert(pair(str[i], ' '));
		}
		i++;
	}
	it = map_chars_find.begin();
	pend = map_chars_find.end();
	for (; it != pend; it++)
	{
		int aa = it->first +32;
		index = map_chars_find.find(aa);
		if (index != map_chars_find.end())
		{
			a++;
		}
	}
	cout << "::" << a << endl;
	return a;
}

解法二:用两个长度是26的bool类型数组存储已找到的字符。

int count_of_letter_both_upper_lower_case_bool(const char *str)
{
	int letter_count = 0;
	bool letter_lower[26] = {0};
	bool letter_upper[26] = {0};
	int i = 0;
	while(str[i] != '\0')
	{
		if(str[i] >= 'A' && str[i] <= 'Z')
		{
			letter_upper[str[i] - 65] = true;
		}
		else if(str[i] >= 'a' && str[i] <= 'z')
		{
			letter_lower[str[i] - 97] = true;
		}
		i++;
	}
	for (int j = 0;j < 26;j++)
	{
		if (letter_lower[j] == true &&letter_upper[j] == true)
		{
			letter_count++;
		}
	}
	return letter_count;
}

 

你可能感兴趣的:(C++)