卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16637本站已运行3320

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

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

介绍

一个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”</p><p>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<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);
}

Output

Input String − I want to learn at TutorialsPoint
First and last words of each string − 
II wt to ln at Tt

Conclusion

在C++字符串中,大多数字符操作可以通过一次遍历字符串来完成。可以使用它们在常数时间内的位置轻松访问字符串的字符。字符串的索引从0开始,以字符串长度-1的值结束。

卓越飞翔博客
上一篇: 将以下内容翻译为中文:最大化从数组中选择的数字的和,使其变为空
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏