首页 >后端开发 >C++ >打印字符串中每个单词的最后一个字符

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

WBOY
WBOY转载
2023-09-17 09:37:021196浏览

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

介绍

C++ strings are essentially a combination of words used as a storage unit to contain alphanumeric data. The words in a string are associated with the following properties −

  • 单词的位置从0开始。

  • Every word is associated with a different length.

  • The characters combine together to form words, which eventually form sentences.

  • 默认情况下,单词之间由空格字符分隔。

  • Every word contains at least one character.

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

Sample Example

示例1−

str − “Key word of a string”
Output − y d f a g

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

在这篇文章中,我们将开发一段代码,使用索引运算符提取每个单词的最后一个字符,然后分别访问前一个字符。

Syntax

str.length()

length()

的中文翻译为:

length()

在C++中,length()方法用于计算字符串中的字符数。它按照字符串的线性顺序工作。

Algorithm

  • An input string, str is accepted.

  • The length of the string is computed using the length() method and stored in len variable.

  • An iteration of the string is performed, using the for loop i.

  • Each time the character at ith position is extracted, stored in variable ch

  • If this character is equivalent to the last index of the string, that is len-1, it is displayed.

  • 如果这个字符等于空格字符,则显示第i-1个索引字符,因为它是前一个单词的最后一个字符。

Example

下面的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

Conclusion

在C++中,字符串的句子格式中,所有单词都由空格字符分隔。字符串的每个单词由大写和小写字符组成。使用相应的索引很容易提取这些字符并对其进行操作。

以上是打印字符串中每个单词的最后一个字符的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除