C++ 打印字符串中每个单词的第一个和最后一个字符
介绍
C++字符串是一串连续的存储字母、数字和特殊字符。字符串具有以下属性:
- 每个C++字符串都与固定长度关联。
-
可以轻松进行字符操作。
-
字符串由用空格分隔的单词组成。
在本文中,我们将开发一段代码,输入一个字符串,并显示字符串中每个单词的最后一个字符。让我们通过以下示例来更好地理解这个主题:
示例
示例1 –
str − “Key word of a string”
Output − Ky wd of aa sg
例如,在这个字符串的第四个单词中,只有一个字符“a”出现,因此这是这个字符串的第一个和最后一个字符。
在本文中,我们将开发一段代码,使用索引运算符提取每个单词的最后一个字符。在这里,我们将开发一段代码,使用索引运算符提取每个单词的最后一个字符,并分别访问前一个字符及后一个字符。
语法
str.length()
length()
C++ 中的长度 () 方法用于计算字符串中的字符数。内置的 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的值结束。