1. 程式人生 > >字串輸出對齊問題

字串輸出對齊問題

問題描述:
  線上的筆試題,記得不是很清楚了,大概的如下:
1、第一行輸入一個整數,代表字串對齊輸出的每行的大小(假設字型等大小),第二行輸入一個行字串,每個單詞之間用一個空格分割。
2、分行輸出後每行的末尾不能是空格,除了最後一行外必須是‘\n’,除最後一行外。
3、單詞不能拆分。在前面的句子中增加空格的時候遵循大間隔在前,小間隔在後,且每個間隔之間的“間隔差”不能超過一。也就是空格數應該是3,3,2,1這種

問題分析:
  看到問題的第一想法是用一個佇列儲存輸入的字串,然後用根據需要輸出的大小去取佇列元素作為輸出子串,然後判斷子串最後一個字元的來分幾種情況:
  1、是空格,則空格前一個為輸出的結尾,並且在子串第一個空格地方增添空格
  2、是英文字母,首先判斷後一個字元如果是空格,則子串直接輸出。如果後一個不是空格,則查詢自子串中最有一個空格的位置,計算需要增添的空格數目。然後又依照大間隔在前,小間隔在後的規則增加規則。
  3、非空格和英文字母(如符號等)。直接輸出子串。
 
(好吧,這其實是一道前端的面試題,本來使用js來做的,然後我對js一點都不懂,就用c++ 來做了,就當作對於c++ 的string的相關函式的學習);
程式碼如下:

int main(int argc, char ** argv)
{
    using namespace std;
    int LineWidth =25;
    //cin >> LineWidth;
    //cin.ignore();
    string text;
    //getline(cin,text);
    text = "Company Profile 51 credit card was established in May 2012, the first to help users a key to manage credit card billing '51 credit card housekeeper' APP, has now developed into the management of China's largest credit card bill of lading mobile Internet companies with more than 70 million bank certified Quality users, management of China over active credit card bills."
; bool isend = false; do { if (text.size() >= LineWidth) { string outtxt; outtxt = text.substr(0, LineWidth); char pin = outtxt[outtxt.length() - 1]; if (pin == ' ') { outtxt.erase(outtxt.length() - 1
); int ix = outtxt.find_first_of(' '); outtxt.insert(ix, " "); text = text.substr(LineWidth,text.length()-1); }else if (isalpha(pin)) { if (text.size() == LineWidth|| text[LineWidth]==' ') { text = text.substr(LineWidth,text.length()-1); } else { int ix = outtxt.find_last_of(' '); outtxt = text.substr(0, ix); int addspace = LineWidth - outtxt.length(); int orispace = 0; std::vector<int> indexspace; for (int i = 0; i < outtxt.length(); i++) { if (outtxt[i] == ' ') { indexspace.push_back(i); orispace++; } } for (int k = 0,i=0; i < addspace; i++,k++) { if (k >=indexspace.size()) { k = 0; } outtxt.insert(indexspace[k], " "); for (int j=k+1;j<indexspace.size();j++) { indexspace[j]++; } } text = text.substr(ix,text.length()-1); } } else { text = text.substr(LineWidth, text.length() - 1); } cout << outtxt<<'\n'; } else if (text.size()>0) { cout << text; text.clear(); } if (text.size()==0) { isend = true; } } while (!isend); //int wait; //cin >> wait; }

輸出的結果如下:
這裡寫圖片描述

這裡有一個問題,就是每個行的行頭的空格沒有去掉。因為主要是想學習一下string函式的用法,所以也就不改了,權當鍛鍊一下程式設計能力