
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.
在本文中,我们将开发一段代码,该代码以一个字符串作为输入,并显示该字符串中每个单词的最后一个字符。让我们看下面的示例以更好地理解这个主题 -
示例1−
str − “Key word of a string” Output − y d f a g
例如,在这个字符串的第四个单词中,只有一个字符出现,因此这是该字符串的最后一个字符。
在这篇文章中,我们将开发一段代码,使用索引运算符提取每个单词的最后一个字符,然后分别访问前一个字符。
本文档主要讲述的是Ruby on Rails字符串处理;在Ruby中创建一个字符串有多种方式。可以有两种方式表示一个字符串:用一对单引号包围字符('str')或用一对双引号包围字符("str") 这两种形式的区别在于对于包围的字符串的处理,用双引号构造的字符串能处理更多的转移字符。 希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
0
str.length()
在C++中,length()方法用于计算字符串中的字符数。它按照字符串的线性顺序工作。
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个索引字符,因为它是前一个单词的最后一个字符。
下面的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++中,字符串的句子格式中,所有单词都由空格字符分隔。字符串的每个单词由大写和小写字符组成。使用相应的索引很容易提取这些字符并对其进行操作。
以上就是打印字符串中每个单词的最后一个字符的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号