原文:
给定字符串 str ,任务是打印字符串中每个单词的最后一个字符。
示例:
输入: str = "极客换极客" 输出: s r s
输入: str = "计算机应用程序" 输出: r s
方法:在给定字符串的末尾添加一个空格,即 " " ,这样字符串中的最后一个单词后面也会跟一个空格,就像字符串中的所有其他单词一样。现在开始逐字符遍历字符串,并打印每个后跟空格的字符。 以下是上述办法的实施情况:
c
// cpp implementation of the approach
#include
using namespace std;
// function to print the last character
// of each word in the given string
void printlastchar(string str)
{
// now, last word is also followed by a space
str = str " ";
for (int i = 1; i < str.length(); i )
{
// if current character is a space
if (str[i] == ' ')
// then previous character must be
// the last character of some word
cout << str[i - 1] << " ";
}
}
// driver code
int main()
{
string str = "geeks for geeks";
printlastchar(str);
}
// this code is contributed by
// surendra_gangwar
java 语言(一种计算机语言,尤用于创建网站)
// java implementation of the approach
class gfg {
// function to print the last character
// of each word in the given string
static void printlastchar(string str)
{
// now, last word is also followed by a space
str = str " ";
for (int i = 1; i < str.length(); i ) {
// if current character is a space
if (str.charat(i) == ' ')
// then previous character must be
// the last character of some word
system.out.print(str.charat(i - 1) " ");
}
}
// driver code
public static void main(string s[])
{
string str = "geeks for geeks";
printlastchar(str);
}
}
python 3
# function to print the last character
# of each word in the given string
def printlastchar(string):
# now, last word is also followed by a space
string = string " "
for i in range(len(string)):
# if current character is a space
if string[i] == ' ':
# then previous character must be
# the last character of some word
print(string[i - 1], end = " ")
# driver code
string = "geeks for geeks"
printlastchar(string)
# this code is contributed by shrikant13
c
// c# implementation of the approach
using system;
class gfg
{
// function to print the last character
// of each word in the given string
static void printlastchar(string str)
{
// now, last word is also followed by a space
str = str " ";
for (int i = 1; i < str.length; i )
{
// if current character is a space
if (str[i] == ' ')
// then previous character must be
// the last character of some word
console.write(str[i - 1] " ");
}
}
// driver code
public static void main()
{
string str = "geeks for geeks";
printlastchar(str);
}
}
// this code is contributed by ryuga
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
output:
s r s
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处