Reputation: 1
Create a function that will encode any given string into a compressed form! Have the function RebelEncoding(string str)
take a string parameter and return the encoded string, The returned value must not contain any punctuation.
static string RebelEncoding(string str)
{
if (str == null || str == "")
{
return str;
}
StringBuilder sb = new StringBuilder();
char prevChar = str[0];
int count = 1;
for(int i = 1;i < str.Length;i++)
{
if (!Char.IsPunctuation(str[i]))
{
if (str[i] == prevChar)
{
count++;
}
else
{
sb.Append(count);
sb.Append(prevChar);
prevChar = str[i];
count = 1;
}
}
}
sb.Append(count);
sb.Append(prevChar);
string results = sb.ToString();
if (results.Length >= str.Length)
{
return results;
}
return results;
}
static void Main(string[] args)
{
string results;
results=RebelEncoding("Squad Beta-111 attack!");
Console.WriteLine(results);
Console.ReadLine();
}
My output:
1S1q1u1a1d1 1B1e1t1a311 1a2t1a1c1k
Desired output:
1S1q1u1a1d 1B1e1t1a31 1a2t1a1c1k
Upvotes: -1
Views: 95
Reputation: 644
I just added && str[i] != ' '
condition to your if statement, since the problem was with whitespaces in your string.
and also added else if (str[i] == ' ')
logic for when it reaches white spaces.
for(int i = 1;i < str.Length;i++)
{
if (!Char.IsPunctuation(str[i]) && str[i] != ' ')
{
if (str[i] == prevChar)
{
count++;
}
else
{
sb.Append(count);
sb.Append(prevChar);
prevChar = str[i];
count = 1;
}
}
else if (str[i] == ' ')
{
sb.Append(count);
sb.Append(prevChar);
sb.Append(' '); // Append space character
while (i + 1 < str.Length && str[i + 1] == ' ')
{
i++;
}
prevChar = i + 1 < str.Length ? str[i + 1] : ' ';
count = 0;
}
}
Upvotes: 1
Reputation: 64
Use below to clean your string:
string cleanStr = Regex.Replace(str, @"[^\w\s]", "");
Upvotes: 0