> 백엔드 개발 > C++ > 본문

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

WBOY
풀어 주다: 2023-09-17 09:37:02
앞으로
1064명이 탐색했습니다.

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

介绍

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
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 
로그인 후 복사

输出

Input String : Programming at TutorialsPoint
Last words of each word in a string : 
g t t
로그인 후 복사

Conclusion

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

위 내용은 打印字符串中每个单词的最后一个字符의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!