通过用长度替换除第一个和最后一个以外的所有字符来缩写给定的字符串
给定字符串str,任务是将给定字符串转换为其缩写形式:第一个字符,第一个和最后一个字符之间的字符数,以及字符串的最后一个字符。
例子:
Input: str = “internationalization”
Output: i18n
Explanation: First letter ‘i’, followed by number of letters between ‘i’ and ‘n’ i.e. 18, and the last letter ‘n’.
Input: str = “geeksforgeeks”
Output: g11s
方法:给定的问题是一个基于实现的问题,可以通过以下步骤解决:
- 打印给定字符串str[0]的第一个字符。
- 将字符串的长度存储在变量len中并打印len – 2 。
- 打印字符串的最后一个字符,即str[len -1] 。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function to convert the given
// string into its abbreviation
void abbreviateWord(string str)
{
// Stores the length of the string
int len = str.size();
// Print 1st character
cout << str[0];
// Print count of characters
// in between
cout << len - 2;
// Print last character
cout << str[len - 1];
}
// Driver Code
int main()
{
string str = "internationalization";
abbreviateWord(str);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class GFG
{
// Function to convert the given
// string into its abbreviation
static void abbreviateWord(String str)
{
// Stores the length of the string
int len = str.length();
// Print 1st character
System.out.print(str.charAt(0));
// Print count of characters
// in between
System.out.print(len - 2);
// Print last character
System.out.print(str.charAt(len - 1));
}
// Driver Code
public static void main(String args[])
{
String str = "internationalization";
abbreviateWord(str);
}
}
// This code is contributed by Samim Hossain Mondal.
Python3
# Python code for the above approach
# Function to convert the given
# string into its abbreviation
def abbreviateWord(str):
# Stores the length of the string
_len = len(str);
# Print 1st character
print(str[0], end="");
# Print count of characters
# in between
print(_len - 2, end="");
# Print last character
print(str[_len - 1], end="");
# Driver Code
str = "internationalization";
abbreviateWord(str);
# This code is contributed gfgking
C#
// C# program of the above approach
using System;
class GFG
{
// Function to convert the given
// string into its abbreviation
static void abbreviateWord(string str)
{
// Stores the length of the string
int len = str.Length;
// Print 1st character
Console.Write(str[0]);
// Print count of characters
// in between
Console.Write(len - 2);
// Print last character
Console.Write(str[len - 1]);
}
// Driver Code
public static void Main()
{
string str = "internationalization";
abbreviateWord(str);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
i18n
时间复杂度: O(1)
辅助空间: O(1)