Abbreviate given string by replacing all characters with length except the first and last
Given string str, the task is to convert the given string into its abbreviation of the form: first character, number of characters between first and last character, and the last character of the string.
Examples:
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
Approach: The given problem is an implementation based problem that can be solved by following the below steps:
- Print the 1st character of the given string str[0].
- Store the length of the string in a variable len and print len – 2.
- Print the last character of the string i.e, str[len -1].
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void abbreviateWord(string str)
{
int len = str.size();
cout << str[0];
cout << len - 2;
cout << str[len - 1];
}
int main()
{
string str = "internationalization" ;
abbreviateWord(str);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
static void abbreviateWord(String str)
{
int len = str.length();
System.out.print(str.charAt( 0 ));
System.out.print(len - 2 );
System.out.print(str.charAt(len - 1 ));
}
public static void main(String args[])
{
String str = "internationalization" ;
abbreviateWord(str);
}
}
|
Python3
def abbreviateWord( str ):
_len = len ( str );
print ( str [ 0 ], end = "");
print (_len - 2 , end = "");
print ( str [_len - 1 ], end = "");
str = "internationalization" ;
abbreviateWord( str );
|
C#
using System;
class GFG
{
static void abbreviateWord( string str)
{
int len = str.Length;
Console.Write(str[0]);
Console.Write(len - 2);
Console.Write(str[len - 1]);
}
public static void Main()
{
string str = "internationalization" ;
abbreviateWord(str);
}
}
|
Javascript
<script>
function abbreviateWord(str)
{
let len = str.length;
document.write(str[0]);
document.write(len - 2);
document.write(str[len - 1]);
}
let str = "internationalization" ;
abbreviateWord(str);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
10 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...