1. 程式人生 > >String Task解決方案【CodeForces - 118A 】

String Task解決方案【CodeForces - 118A 】

String Task解決分析

謹以此文章紀念第一次ACM訓練…

題目

Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:

  • deletes all the vowels,
  • inserts a character “.” before each consonant,
  • replaces all uppercase consonants with corresponding lowercase ones.

Vowels are letters “A”, “O”, “Y”, “E”, “U”, “I”, and the rest are consonants. The program’s input is exactly one string, it should return the output as a single string, resulting after the program’s processing the initial string.
Help Petya cope with this easy task.

Time limit Memory limit SourceCodeforces Tag Editorial
2000 ms 262144 kB Beta Round #89 (Div. 2) simplementation strings *1100 Announcement Tutorial #1 Tutorial #2

Input

The first line represents input string of Petya’s program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive.

Output

Print the resulting string. It is guaranteed that this string is not empty.

Example

input output
tour .t.r
Codeforces .c.d.f.r.c.s
aBAcAba .b.c.b

問題連結:CodeForces - 118A

問題描述

輸入一串含有大寫和小寫的字母,將其中的母音字母1刪除,並在每一個子音字母前加上一個點(.),最後將所有的大寫字母換成小寫字母。

問題分析

首先獲得使用者的輸入存於字串變數中,然後找出其中的母音字母並將其刪除。之後再在剩餘的字母前面統一加點,最後將大寫換成小寫。

AC通過的C++語言程式程式碼如下:

#include<string>
#include <iostream>
using namespace std;
int main()
{
	string str;
	cin >> str;
	for (int i = 0; i < str.size(); i++)
		if (str[i] == 'A' || str[i] == 'O' || str[i] == 'Y' || str[i] == 'E' || str[i] == 'U' || str[i] == 'I' || str[i] == 'a' || str[i] == 'o' || str[i] == 'y' || str[i] == 'e' || str[i] == 'u' || str[i] == 'i')
		{
			str = str.erase(i, 1);
			i--;
		}
	for (int i = 0; i < str.size(); i += 2)
		str.insert(i, ".");
	for (int n = 0; n < str.size(); n++)
		if (str[n] >= 65 && str[n] <= 90)str[n] += 32;
	cout << str << endl;
	return 0;
}

程式碼分析

此程式使用到了string類,所以要包括標頭檔案string。

首先是刪除母音字母:

//刪除字串陣列中的母音字母
for (int i = 0; i < str.size(); i++)
		if (str[i] == 'A' || str[i] == 'O' || str[i] == 'Y' || str[i] == 'E' || str[i] == 'U' || str[i] == 'I' || str[i] == 'a' || str[i] == 'o' || str[i] == 'y' || str[i] == 'e' || str[i] == 'u' || str[i] == 'i')
		{
			str = str.erase(i, 1);
			i--;
		}

這裡需要注意的是當第i個字母被刪除之後,由於後面的字母會補上來,第i個字母就會變成後面一個字母,然而如果後面一個字母是母音字母而i直接自增就會導致這個字母被跳過,其後果就是有殘留的母音字母,解決辦法就是在刪除字母之後加一行i- -以防下一個字母被跳過。

之後由於字串陣列中的母音字母已經全部被刪除,剩餘的必然全都是子音字母。
於是直接在每個字母前加點:

//在子音字母前加點
for (int i = 0; i < str.size(); i += 2)
		str.insert(i, ".");

這裡要注意的是加了點之後字串陣列元素會整體右移,所以要把i切換成下一個字母就等把i加2,而非加1。

最後將所有大寫字母換成小寫字母2

//將大寫字母換為小寫字母
for (int n = 0; n < str.size(); n++)
		if (str[n] >= 65 && str[n] <= 90)str[n] += 32;

然後輸出陣列就大功告成啦!


  1. 母音字母為:“A”, “O”, “Y”, “E”, “U”, “I”,剩餘的字母全是子音字母 ↩︎

  2. 大寫字母與小寫字母的ASCII碼值相差32 ↩︎