打印字符串中每个单词的第一个和最后一个字符

2023年 8月 29日 45.7k 0

打印字符串中每个单词的第一个和最后一个字符

介绍

一个C++字符串是连续存储的字母数字字符和特殊字符。字符串具有以下属性−

  • Every C++ string is associated with a fixed length.

  • Character operations can be easily performed with the string characters.

  • 一个字符串由单词组成,单词之间用空格分隔。

在本文中,我们将开发一个代码,该代码以字符串作为输入,并显示字符串中每个单词的最后一个字符。让我们看下面的示例以更好地理解这个主题 -

示例例子

Example 1 −

str − “Key word of a string”

Output − Ky wd of aa sg

登录后复制

例如,在此字符串的第四个单词中,只出现了一个字符“a”,因此这是该字符串的第一个和最后一个字符。

在本文中,我们将开发一个代码,使用索引操作符提取每个单词的最后一个字符。在这里,我们将开发一个代码,使用索引操作符提取每个单词的最后一个字符,并分别访问前面的字符。

Syntax

str.length()

登录后复制

length()

的翻译为:

length()

The length() method in C++ is used to compute the number of characters in the string. The in-built length() method works in linear time.

算法

  • 接受一个输入字符串,str。

  • 使用length()方法计算字符串的长度,并将其存储在len变量中。

  • 使用for循环i执行字符串的迭代。

  • 将字符串的特定字符提取并存储在变量ch中。

  • Each time the character at ith position is extracted

  • If this index is equivalent to the first index of the string, it is printed

  • 如果此索引等于字符串的最后一个索引,则显示 len-1 字符。

  • If this character is equivalent to the space character, then the i-1th index character is displayed, since it is the last character of the previous word.

  • 由于下一个单词的第一个字符,i+1索引也被打印出来。

Example

以下C++代码片段用于输入一个示例字符串,并计算字符串中每个单词的第一个和最后一个字符 −

//including the required libraries
#include
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

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论