列印字串中每個單詞的首字元和尾字元
引言
C++ 字串是字母數字字元以及特殊字元的連續儲存。字串具有以下屬性:
每個 C++ 字串都與一個固定長度相關聯。
可以使用字串字元輕鬆執行字元操作。
字串由單片語成,單詞之間用空格分隔。
在本文中,我們將開發一段程式碼,該程式碼以字串作為輸入,並顯示字串中每個單詞的最後一個字元。讓我們看下面的例子來更好地理解這個主題:
示例
示例 1:
str − “Key word of a string”
Output − Ky wd of aa sg
例如,在這個字串的第四個單詞中,只有一個字元“a”,因此這是這個字串的首字元和尾字元。
在本文中,我們將開發一段程式碼,使用索引運算子提取每個單詞的最後一個字元。在這裡,我們將開發一段程式碼,使用索引運算子提取每個單詞的最後一個字元,然後分別訪問後續的前面字元。
語法
str.length()
length()
C++ 中的 length() 方法用於計算字串中的字元數。內建的 length() 方法線上性時間內工作。
演算法
接受輸入字串 str。
使用 length() 方法計算字串的長度,並將其儲存在 len 變數中。
使用 for 迴圈 i 對字串進行迭代。
提取字串的特定字元並將其儲存在變數 ch 中。
每次都提取第 i 個位置的字元
如果此索引等效於字串的第一個索引,則列印它
如果此索引等效於字串的最後一個索引,則顯示 len-1 字元。
如果此字元等效於空格字元,則顯示 i-1 索引字元,因為它是前一個單詞的最後一個字元。
由於下一個單詞的第一個字元,也列印 i+1 索引。
示例
以下 C++ 程式碼片段用於將示例字串作為輸入,並計算字串中每個單詞的首字元和尾字元:
//including the required libraries
#include<bits/stdc++.h>
using namespace std;
//compute the first and last characters of a string
void wordfirstandlastchar(string str) {
// getting length of the string
int len = str.length();
for (int i = 0; i <len ; i++) {
char ch = str[i];
//print the first word of the string
if (i == 0)
cout<<ch;
//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
//print the next character of the next word
char lst = str[i-1];
char nxt = str[i+1];
cout<<lst<<" "<<nxt;
}
}
}
//calling the method
int main() {
//taking a sample string
string str = "I want to learn at TutorialsPoint";
cout<<"Input String : "<< str <<"\n";
//getfirstandlast characters
cout<<"First and last words of each string : \n";
wordfirstandlastchar(str);
}
輸出
Input String − I want to learn at TutorialsPoint First and last words of each string − II wt to ln at Tt
結論
大多數 C++ 字串中的字元操作可以使用對字串的單次遍歷來執行。可以使用字元在字串中的位置在恆定時間內輕鬆訪問字串的字元。字串的索引從 0 開始,到字串長度-1 值結束。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP