原文:
给定一个字符串,任务是打印字符串中每个单词的第一个和最后一个字符。 例:
input: geeks for geeks
output: gs fr gs
input: computer applications
output: cr as
接近t2】
- 从第一个字母到最后一个字母循环。
- 打印字符串的第一个和最后一个字母。
- 如果字符串中有空格,则打印位于空格前和空格后的字符。
下面是上述方法的实现。
c
// cpp program to print
// the first and last character
// of each word in a string'
#include
using namespace std;
// function to print the first
// and last character of each word.
void firstandlast(string str)
{
int i;
for (i = 0; i < str.length(); i )
{
// if it is the first word
// of the string then print it.
if (i == 0)
cout<
java 语言(一种计算机语言,尤用于创建网站)
// java program to print
// the first and last character
// of each word in a string
class gfg {
// function to print the first
// and last character of each word.
static void firstandlast(string str)
{
int i;
for (i = 0; i < str.length(); i ) {
// if it is the first word
// of the string then print it.
if (i == 0)
system.out.print(str.charat(i));
// if it is the last word of the string
// then also print it.
if (i == str.length() - 1)
system.out.print(str.charat(i));
// if there is a space
// print the successor and predecessor
// to space.
if (str.charat(i) == ' ') {
system.out.print(str.charat(i - 1)
" "
str.charat(i 1));
}
}
}
// driver code
public static void main(string args[])
{
string str = "geeks for geeks";
firstandlast(str);
}
}
python 3
# python3 program to print
# the first and last character
# of each word in a string'
# function to print the first
# and last character of each word.
def firstandlast(string):
for i in range(len(string)):
# if it is the first word
# of the string then print it.
if i == 0:
print(string[i], end = "")
# if it is the last word of the string
# then also print it.
if i == len(string) - 1:
print(string[i], end = "")
# if there is a space
# print the successor and predecessor
# to space.
if string[i] == " ":
print(string[i - 1],
string[i 1], end = "")
# driver code
if __name__ == "__main__":
string = "geeks for geeks"
firstandlast(string)
# this code is contributed by
# sanjeev2552
c
// c# program to print
// the first and last character
// of each word in a string
using system;
class gfg
{
// function to print the first
// and last character of each word.
static void firstandlast(string str)
{
int i;
for (i = 0; i < str.length; i )
{
// if it is the first word
// of the string then print it.
if (i == 0)
console.write(str[i]);
// if it is the last word of the string
// then also print it.
if (i == str.length - 1)
console.write(str[i]);
// if there is a space
// print the successor and predecessor
// to space.
if (str[i] == ' ')
{
console.write(str[i - 1]
" "
str[i 1]);
}
}
}
// driver code
public static void main()
{
string str = "geeks for geeks";
firstandlast(str);
}
}
// this code is contributed by ryuga
java 描述语言
output:
gs fr gs
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处