📌  相关文章
📜  删除字符串中每个单词的第一个和最后一个字符

📅  最后修改于: 2022-05-13 01:57:07.581000             🧑  作者: Mango

删除字符串中每个单词的第一个和最后一个字符

给定字符串,任务是删除字符串。
例子:

Input: Geeks for geeks
Output: eek o eek

Input: Geeksforgeeks is best
Output: eeksforgeek  es

方法

  • 根据空间拆分字符串
  • 从第一个字母到最后一个字母循环。
  • 检查字符是单词的开头还是结尾
  • 从字符串中删除此字符。

下面是上述方法的实现。

C++
// C++ program to remove the first
// and last character of each word in a string.
#include
using namespace std;
 
string FirstAndLast(string str)
{
    // add a space to the end of the string
    str+=" ";
         
    string res="",w="";
         
    // traverse the string and extract words
    for(int i=0;i


Java
// Java program to remove the first
// and last character of each word in a string.
 
import java.util.*;
 
class GFG {
    static String FirstAndLast(String str)
    {
 
        // Split the String based on the space
        String[] arrOfStr = str.split(" ");
 
        // String to store the resultant String
        String res = "";
 
        // Traverse the words and
        // remove the first and last letter
        for (String a : arrOfStr) {
            res += a.substring(1, a.length() - 1) + " ";
        }
 
        return res;
    }
 
    // Driver code
    public static void main(String args[])
    {
        String str = "Geeks for Geeks";
        System.out.println(str);
        System.out.println(FirstAndLast(str));
    }
}


Python3
# Python3 program to remove the first
# and last character of each word in a string.
 
def FirstAndLast(string) :
     
    # Split the String based on the space
    arrOfStr = string.split();
 
    # String to store the resultant String
    res = "";
 
    # Traverse the words and
    # remove the first and last letter
    for a in arrOfStr :
        res += a[1:len(a) - 1] + " ";
     
    return res;
     
# Driver code
if __name__ == "__main__" :
     
    string = "Geeks for Geeks";
     
    print(string);
    print(FirstAndLast(string));
 
# This code is contributed by Ryuga


C#
// C# program to remove the first
// and last character of each word in a string.
using System;
 
class GFG
{
    static String FirstAndLast(String str)
    {
 
        // Split the String based on the space
        String[] arrOfStr = str.Split(' ');
 
        // String to store the resultant String
        String res = "";
 
        // Traverse the words and
        // remove the first and last letter
        foreach (String a in arrOfStr)
        {
            res += a.Substring(1, a.Length-2) + " ";
        }
 
        return res;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        String str = "Geeks for Geeks";
        Console.WriteLine(str);
        Console.WriteLine(FirstAndLast(str));
    }
}
 
/* This code contributed by PrinciRaj1992 */


PHP


Javascript


输出:
Geeks for Geeks
eek o eek