列印字串中每個單詞的最後一個字元


介紹

C++ 字串本質上是作為儲存單元來儲存字母數字資料的單詞組合。字串中的單詞具有以下屬性:

  • 單詞位置從 0 開始。

  • 每個單詞都具有不同的長度。

  • 字元組合在一起形成單詞,最終形成句子。

  • 預設情況下,單詞之間用空格字元分隔。

  • 每個單詞至少包含一個字元。

在本文中,我們將開發一個程式碼,該程式碼以字串作為輸入,並顯示字串中每個單詞的最後一個字元。讓我們看下面的例子來更好地理解主題:

示例

示例 1:

str − “Key word of a string”
Output − y d f a g

例如,在這個字串的第四個單詞中,只出現了一個字元,因此這是這個字串的最後一個字元。

在本文中,我們將開發一個程式碼,使用索引運算子提取每個單詞的最後一個字元,然後分別訪問後續的前一個字元。

語法

str.length()

length()

C++ 中的 length() 方法用於計算字串中的字元數。它按照字串時間的線性順序工作。

演算法

  • 接受一個輸入字串 str。

  • 使用 length() 方法計算字串的長度,並將其儲存在 len 變數中。

  • 使用 for 迴圈 i 對字串進行迭代。

  • 每次提取第 i 個位置的字元,並將其儲存在變數 ch 中。

  • 如果此字元等效於字串的最後一個索引,即 len-1,則顯示它。

  • 如果此字元等效於空格字元,則顯示第 i-1 個索引字元,因為它是前一個單詞的最後一個字元。

示例

以下 C++ 程式碼片段用於將樣本字串作為輸入,並計算字串中每個單詞的最後一個字元:

//including the required libraries
#include<bits/stdc++.h>
using namespace std;
//compute last characters of a string 
void  wordlastchar(string str) {
   // getting length of the string 
   int len = str.length();
   for (int i = 0; i <len ; i++) {
      char ch = str[i];
     
      //last word of the string
      if (i == len - 1)
         cout<<ch;
 
      //if a space is encountered, marks the start of new word 
      if (ch == ' ') {
         //print the previous character of the last word 
           
          char lst = str[i-1];
          cout<<lst<<" ";
       }
    }
}
 
//calling the method
int main() {
   //taking a sample string 
   string str = "Programming at TutorialsPoint";
   cout<<"Input String : "<< str <<"\n"; 
   //getfirstandlast characters
   cout<<"Last words of each word in a string : \n";
   wordlastchar(str);
}

輸出

Input String : Programming at TutorialsPoint
Last words of each word in a string : 
g t t

結論

在 C++ 中,字串的句子形式中,所有單詞都用空格字元分隔。字串的每個單詞都由大寫和小寫字元組成。使用它們相應的索引提取這些字元並對其進行操作非常容易。

更新於:2023-07-31

890 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.