C/C++ Programming Learning-Week 9 ③ Sort out the names of medicines

Topic link

Title description

Doctors often do not pay attention to capitalization when writing drug names, and the format is rather confusing. Now you are required to write a program to organize the names of drugs that the doctor writes in confusion into a uniform and standardized format, that is, if the first character of the drug name is a letter, it should be capitalized, and the other letters should be lowercase. Such as sorting "ASPIRIN" and "aspirin" into "Aspirin".

Input format
A number n in the first line indicates that there are n drug names to be sorted, and n does not exceed 100.

The next n lines, each line contains one word, and the length does not exceed 20, indicating the name of the medicine written by the doctor. The drug name consists of letters, numbers and -.

The output format is
n lines, with one word per line, corresponding to the standardized writing of the input drug name.

Sample Input

4
AspiRin
cisapride
2-PENICILLIN
Cefradine-6

Sample Output

Aspirin
Cisapride
2-penicillin
Cefradine-6

Ideas

If the first character of the drug name is a letter, capitalize, and the other letters are lowercase. That is to determine whether the string is an uppercase character.

C++ code 1:

#include<iostream>
using namespace std;
int n, len;
string s;
int main()
{
    
    
	cin >> n;
	for(int i = 0; i < n;++i)
	{
    
    
		cin >> s;
		len = s.size();//获取字符串s的长度
		if(s[0] >= 'a' && s[0] <= 'z')
			s[0] -= 32;//字符的比较的本质是其所对应的ASCII码的比较,而在ASCII码表中,26个英文字母的ASCII码值是紧挨在一起的.所以,如果第一个是字母是小写字母,其ASCII码就在'a'和'z'之间,而ASCII码表中每一个大写字母总是比对应的小写字母的值小32,所以让其减去32使其变成大写字母
		for(int j = 1; j < len; ++j)//遍历除了第一个字符的字符串
			if(s[j] >= 'A' && s[j] <= 'Z')//把大写字母变成小写字母
				s[j] += 32;
		cout<<s<<"\n";
	}
	return 0;
}

C++ code 2:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	string str;
	int n;
	while(cin >> n)
	{
    
    
		while(n--)
		{
    
    
			cin >> str;
			int len = str.length();
			for(int i = 0; i < len; i++)
			{
    
    
				if(i == 0)
				{
    
    
					if(str[i] >= 97 && str[i] <= 122) str[i] -= 32;
				}
				else
				{
    
    
					if(str[i] >= 65 && str[i] <= 90) str[i] += 32;
				}
			}
			cout << str << endl;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113095668