C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
First loop: This counts the number of punctuation characters at the start of the string.
Second loop: This loop counts the punctuation at the end. It iterates in the reverse order.
Info: If no punctuation was found, the method returns the original string. If all characters were punctuation, it returns an empty string.
And: The method returns a substring with the punctuation characters removed in the final case.
Empty StringSubstringC# program that trims punctuation characters
using System;
class Program
{
static void Main()
{
string[] array =
{
"Do you like this site?",
"--cool--",
"...ok!",
"None",
""
};
// Call method on each string.
foreach (string value in array)
{
Console.WriteLine(Program.TrimPunctuation(value));
}
}
/// <summary>
/// TrimPunctuation from start and end of string.
/// </summary>
static string TrimPunctuation(string value)
{
// Count start punctuation.
int removeFromStart = 0;
for (int i = 0; i < value.Length; i++)
{
if (char.IsPunctuation(value[i]))
{
removeFromStart++;
}
else
{
break;
}
}
// Count end punctuation.
int removeFromEnd = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
if (char.IsPunctuation(value[i]))
{
removeFromEnd++;
}
else
{
break;
}
}
// No characters were punctuation.
if (removeFromStart == 0 &&
removeFromEnd == 0)
{
return value;
}
// All characters were punctuation.
if (removeFromStart == value.Length &&
removeFromEnd == value.Length)
{
return "";
}
// Substring.
return value.Substring(removeFromStart,
value.Length - removeFromEnd - removeFromStart);
}
}
Output
Do you like this site
cool
ok
None
Also: If you have a specific requirement, such as removing all punctuation and also all numbers, this sort of solution can come in handy.
Note: A regex could still be used, but it will become comparatively more complex.
Review: We developed a simple looping method that strips leading and trailing punctuation from a string.