显示文本缩写的 C# 程序
给定一个文本,我们需要显示文本的缩写。缩写是任何单词或短语的最短形式。它包含一组字母,这些字母取自单词或短语的完整形式。例如,GeeksforGeeks 的缩写是 GFG,或者 Advance Data Structure 的缩写是 ADS。
例子:
Input : Geeks For Geeks
Output: G.F.G
Input : Data Structures Algorithms
Output: D.S.A
方法:
To print the abbreviation of a text follow the following steps:
- Initialize an empty string (i.e. abbr).
- Append the first letter of string to abbr and also append a ‘ . ‘ to abbr.
- Now the String is iterated from left to right if space or tab or a newline character is encountered then append the next letter to the abbr and also append ‘ . ‘ to the abbr.
- At the end of the iteration, the abbr will have the abbreviation of the given string.
例子:
C#
// C# program to print the abbreviation of a Text
using System;
class GFG{
public static string Abbreviation(string inputstr)
{
string abbr = "";
int i = 0;
abbr += inputstr[0];
abbr += '.';
for(i = 0; i < inputstr.Length - 1; i++)
{
if (inputstr[i] == ' ' || inputstr[i] == '\t' ||
inputstr[i] == '\n')
{
abbr += inputstr[i + 1];
abbr += '.';
}
}
return abbr;
}
// Driver code
public static void Main()
{
string str = "Geeks For Geeks";
string abr = "";
abr = Abbreviation(str);
Console.Write("The Abbreviation : " + abr);
}
}
输出
The Abbreviation : G.F.G.
说明:在这个例子中,我们创建了一个 Abbreviation() 方法,它返回指定字符串的缩写。或者我们可以说它返回一个包含单词第一个字母的字符串,如果单词之前有空格或制表符或字符,则将其添加到 abbr字符串,以及一个 ' 。 ' 也被添加。就像在字符串“Geeks For Geeks”中一样,缩写是 GFG