打印字符串中每个单词的最后一个字符
介绍
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++ 中,字符串的句子形式中,所有单词都用空格字符分隔。字符串的每个单词都由大写和小写字符组成。使用它们相应的索引提取这些字符并对其进行操作非常容易。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP