Error CS1002 At Run Time - Markdown Parser (Headers Only) - c#

"src/Solution.cs(9,12): error CS1002: ; expected"
I cannot work out why I am being shown this error? I have put my code below. I am very inexperienced at c-sharp, I normally work in c++, so maybe a small syntax error somewhere?
public class Challenge
{
public static string MarkdownParser( string markdown )
{
string inputText = markdown;
string outputText;
unsigned int indexOfFirstSpace = 0;
unsigned int inputTextLength = 0;
//Trim Spaces Before & After String
inputText = inputText.Trim();
if (inputText.StartsWith("#")){
//Find Index oF First Space & Store
indexOfFirstSpace = inputText.IndexOf(" ");
if (indexOfFirstSpace > 6){
return inputText;
}
else{
//Find Length Of Input String
inputTextLength = inputText.Length;
//Store Hashes In Own String
string hashes = inputText.Substring(0, indexOfFirstSpace);
//Store header text in string
string headerText = inputText.Substring(indexOfFirstSpace,(inputTextLength - indexOfFirstSpace));
//Trim Spaces From Front
headerText = headerText.TrimStart();
//Build Output
outputText = "<h" + indexOfFirstSpace + ">" + headerText + "</h" + indexOfFirstSpace + ">";
return outputText;
}
}
else {
return inputText;
}
}
}

There are 2 problems here:
You tried to use 'unsigned int'. in C# the keyword for that is uinit.
The returned type for inputText.Length is actually an int, so the fixed code should be:
public class Challenge
{
public static string MarkdownParser(string markdown)
{
string inputText = markdown;
string outputText;
// ---- Changed these variables to Int ----
int indexOfFirstSpace = 0;
int inputTextLength = 0;
//Trim Spaces Before & After String
inputText = inputText.Trim();
if (inputText.StartsWith("#"))
{
//Find Index oF First Space & Store
indexOfFirstSpace = inputText.IndexOf(" ");
if (indexOfFirstSpace > 6)
{
return inputText;
}
else
{
//Find Length Of Input String
inputTextLength = inputText.Length;
//Store Hashes In Own String
string hashes = inputText.Substring(0, indexOfFirstSpace);
//Store header text in string
string headerText = inputText.Substring(indexOfFirstSpace, (inputTextLength - indexOfFirstSpace));
//Trim Spaces From Front
headerText = headerText.TrimStart();
//Build Output
outputText = "<h" + indexOfFirstSpace + ">" + headerText + "</h" + indexOfFirstSpace + ">";
return outputText;
}
}
else
{
return inputText;
}
}
}

Related

Retrieve and update the first number of a string

I have a string that may contain a prefix message with a number
e.g : Prefix1_SomeText
I need to check if the string contains the prefix message, and increment the number in that case.
Or if the string does not contain the prefix, I need to append it
e.g : Prefix2_SomeText.
So far I have this:
string format = "prefix{0}_";
string prefix = "prefix";
string text = "prefix1_65478516548";
if (!text.StartsWith(prefix))
{
text = text.Insert(0, string.Format(format, 1));
}
else
{
int count = int.Parse(text[6].ToString()) + 1;
text = (String.Format(format, count) + "_" + text.Substring(text.LastIndexOf('_') + 1));
}
Is there a simple way of doing it?
You could use a regular expression to check if the text contains the prefix and capture the index :
string prefix = "prefix";
string text = "prefix1_65478516548";
Regex r = new Regex($"{prefix}(\\d+)_(.*)");
var match = r.Match(text);
if (match.Success)
{
int index = int.Parse(match.Groups[1].Value);
text = $"{prefix}{index + 1}_{match.Groups[2].Value}";
}
else
{
text = $"{prefix}1_{text}";
}

Need help finding pattern with Regex [duplicate]

I need to be able to extract a string between 2 tags for example: "00002" from "morenonxmldata<tag1>0002</tag1>morenonxmldata"
I am using C# and .NET 3.5.
Regex regex = new Regex("<tag1>(.*)</tag1>");
var v = regex.Match("morenonxmldata<tag1>0002</tag1>morenonxmldata");
string s = v.Groups[1].ToString();
Or (as mentioned in the comments) to match the minimal subset:
Regex regex = new Regex("<tag1>(.*?)</tag1>");
Regex class is in System.Text.RegularExpressions namespace.
Solution without need of regular expression:
string ExtractString(string s, string tag) {
// You should check for errors in real-world code, omitted for brevity
var startTag = "<" + tag + ">";
int startIndex = s.IndexOf(startTag) + startTag.Length;
int endIndex = s.IndexOf("</" + tag + ">", startIndex);
return s.Substring(startIndex, endIndex - startIndex);
}
A Regex approach using lazy match and back-reference:
foreach (Match match in Regex.Matches(
"morenonxmldata<tag1>0002</tag1>morenonxmldata<tag2>abc</tag2>asd",
#"<([^>]+)>(.*?)</\1>"))
{
Console.WriteLine("{0}={1}",
match.Groups[1].Value,
match.Groups[2].Value);
}
Extracting contents between two known values can be useful for later as well. So why not create an extension method for it. Here is what i do, Short and simple...
public static string GetBetween(this string content, string startString, string endString)
{
int Start=0, End=0;
if (content.Contains(startString) && content.Contains(endString))
{
Start = content.IndexOf(startString, 0) + startString.Length;
End = content.IndexOf(endString, Start);
return content.Substring(Start, End - Start);
}
else
return string.Empty;
}
string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string";
var match = Regex.Match(input, #"FirstString (.+?) SecondString ").Groups[1].Value;
To get Single/Multiple values without regular expression
// For Single
var value = inputString.Split("<tag1>", "</tag1>")[1];
// For Multiple
var values = inputString.Split("<tag1>", "</tag1>").Where((_, index) => index % 2 != 0);
For future reference, I found this code snippet at http://www.mycsharpcorner.com/Post.aspx?postID=15 If you need to search for different "tags" it works very well.
public static string[] GetStringInBetween(string strBegin,
string strEnd, string strSource,
bool includeBegin, bool includeEnd)
{
string[] result ={ "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin);
if (iIndexOfBegin != -1)
{
// include the Begin string if desired
if (includeBegin)
iIndexOfBegin -= strBegin.Length;
strSource = strSource.Substring(iIndexOfBegin
+ strBegin.Length);
int iEnd = strSource.IndexOf(strEnd);
if (iEnd != -1)
{
// include the End string if desired
if (includeEnd)
iEnd += strEnd.Length;
result[0] = strSource.Substring(0, iEnd);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd
+ strEnd.Length);
}
}
else
// stay where we are
result[1] = strSource;
return result;
}
I strip before and after data.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace testApp
{
class Program
{
static void Main(string[] args)
{
string tempString = "morenonxmldata<tag1>0002</tag1>morenonxmldata";
tempString = Regex.Replace(tempString, "[\\s\\S]*<tag1>", "");//removes all leading data
tempString = Regex.Replace(tempString, "</tag1>[\\s\\S]*", "");//removes all trailing data
Console.WriteLine(tempString);
Console.ReadLine();
}
}
}
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
public string between2finer(string line, string delimiterFirst, string delimiterLast)
{
string[] splitterFirst = new string[] { delimiterFirst };
string[] splitterLast = new string[] { delimiterLast };
string[] splitRes;
string buildBuffer;
splitRes = line.Split(splitterFirst, 100000, System.StringSplitOptions.RemoveEmptyEntries);
buildBuffer = splitRes[1];
splitRes = buildBuffer.Split(splitterLast, 100000, System.StringSplitOptions.RemoveEmptyEntries);
return splitRes[0];
}
private void button1_Click(object sender, EventArgs e)
{
string manyLines = "Received: from exim by isp2.ihc.ru with local (Exim 4.77) \nX-Failed-Recipients: rmnokixm#gmail.com\nFrom: Mail Delivery System <Mailer-Daemon#isp2.ihc.ru>";
MessageBox.Show(between2finer(manyLines, "X-Failed-Recipients: ", "\n"));
}

Formatting a multiline string to be printed on a receipt

I am trying to print a multiline string on a paper from my windows forms application and it does print fine but the formatting is applying only to the first line which is being printed slightly to the right and other lines are being aligned to left for which I would like all the lines to be printed just like the first line
Example
ID : value
Head : value
Hand : value
as you can see from the above ID is printer slightly to the right but head and hand lines are not aligned with the first line
sb.Append(strTempMessage + NEW_LINE);
strTempMessage = AlignNumeric(" ", PAGE_LEFT_MARGIN);
strTempMessage += AlignMessage(strPickSlipNote,0);
sb.Append(strTempMessage + NEW_LINE);
public string AlignMessage(string strMessage, int intBeginningBlankSpace)
{
strMessage = strMessage.Trim();
return AlignNumeric(strMessage, intBeginningBlankSpace);
}
public string AlignNumeric(string strMessage, int intBeginningBlankSpace)
{
intBeginningBlankSpace += strMessage.Length;
if (intBeginningBlankSpace > 0)
return strMessage.PadLeft(intBeginningBlankSpace, ' ');
else
return strMessage;
}
what changes should I make to get all the lines aligned?
I am not too sure if its the most efficient way doing this but you can add tab after appending new line e.g. sb.Append(strTempMessage + NEW_LINE + "\t");
This helped solve
public string FormatPickSlipNoteLines(string input)
{
if (string.IsNullOrEmpty(input))
return "";
else if (input.Length < PAGE_COLUMN_SIZE)
return ALIGN_PAGE_CENTER + input + ALIGN_PAGE_LEFT;
else
{
string[] str = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sbFormatter = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
sbFormatter.Append(" " + str[i] + NEW_LINE);
}
return sbFormatter.Append(NEW_LINE + ALIGN_PAGE_LEFT).ToString();
}
}

Convert string to GSM 7-bit using C#

How can I convert a string to correct GSM encoded value to be sent to a mobile operator?
Below is a port of gnibbler's answer, slightly modified and with a detailed explantation.
Example:
string output = GSMConverter.StringToGSMHexString("Hello World");
// output = "48-65-6C-6C-6F-20-57-6F-72-6C-64"
Implementation:
// Data/info taken from http://en.wikipedia.org/wiki/GSM_03.38
public static class GSMConverter
{
// The index of the character in the string represents the index
// of the character in the respective character set
// Basic Character Set
private const string BASIC_SET =
"#£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?" +
"¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
// Basic Character Set Extension
private const string EXTENSION_SET =
"````````````````````^```````````````````{}`````\\````````````[~]`" +
"|````````````````````````````````````€``````````````````````````";
// If the character is in the extension set, it must be preceded
// with an 'ESC' character whose index is '27' in the Basic Character Set
private const int ESC_INDEX = 27;
public static string StringToGSMHexString(string text, bool delimitWithDash = true)
{
// Replace \r\n with \r to reduce character count
text = text.Replace(Environment.NewLine, "\r");
// Use this list to store the index of the character in
// the basic/extension character sets
var indicies = new List<int>();
foreach (var c in text)
{
int index = BASIC_SET.IndexOf(c);
if(index != -1) {
indicies.Add(index);
continue;
}
index = EXTENSION_SET.IndexOf(c);
if(index != -1) {
// Add the 'ESC' character index before adding
// the extension character index
indicies.Add(ESC_INDEX);
indicies.Add(index);
continue;
}
}
// Convert indicies to 2-digit hex
var hex = indicies.Select(i => i.ToString("X2")).ToArray();
string delimiter = delimitWithDash ? "-" : "";
// Delimit output
string delimited = string.Join(delimiter, hex);
return delimited;
}
}
The code of Omar Didn't work for me. But I found The actual code that works:
public static string Encode7bit(string s)
{
string empty = string.Empty;
for (int index = s.Length - 1; index >= 0; --index)
empty += Convert.ToString((byte)s[index], 2).PadLeft(8, '0').Substring(1);
string str1 = empty.PadLeft((int)Math.Ceiling((Decimal)empty.Length / new Decimal(8)) * 8, '0');
List<byte> byteList = new List<byte>();
while (str1 != string.Empty)
{
string str2 = str1.Substring(0, str1.Length > 7 ? 8 : str1.Length).PadRight(8, '0');
str1 = str1.Length > 7 ? str1.Substring(8) : string.Empty;
byteList.Add(Convert.ToByte(str2, 2));
}
byteList.Reverse();
var messageBytes = byteList.ToArray();
var encodedData = "";
foreach (byte b in messageBytes)
{
encodedData += Convert.ToString(b, 16).PadLeft(2, '0');
}
return encodedData.ToUpper();
}

how to increase the value of an integer in a string

Ok I currently have this code
public int i = 0; //this is outside of the private void button1_click
string str = txtEmail.Text;
int pos = str.LastIndexOf("#");
string str2 = str.Substring(pos);
string str3 = str.Substring(0, str.LastIndexOf("#"));
txtEmail.Text = str3 + i++ + str2;
it splits the email into 2 string then combines them with an integer between them, But I want it to change the integer. But that code just makes it lets saying the text becomes awesome1#email.com when i press the button to increase the 1 to a 2 it just does this instead. awesome12#email.com and so on. how do i get it to just add 1 to the 1 and not put a 2 next to the 1?
I tested the following and it looks like it solves your problem. Change this line of yours:
string str = txtEmail.Text;
To this:
string str = txtEmail.Text.Replace(string.Format("{0}#", i - 1), "#");
It sets it up so that your email addresses will be in the form of:
awesome1#email.com
awesome2#email.com
awesome3#email.com
etc.
Not sure where i is coming from in this code but hopefully this will work
string str = txtEmail.Text;
int pos = str.LastIndexOf("#");
string str2 = str.Substring(pos);
string str3 = str.Substring(0, str.LastIndexOf("#"));
txtEmail.Text = str3 + (i++).ToSting() + str2;
This should work:
String email = "awesome1#email.com";
String[] tokens = email.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
const String allowed = "0123456789";
String part1 = "";
String numberStr = "";
foreach (char c in tokens[0].Reverse())
{
if (allowed.Contains(c) && part1.Length==0)
{
numberStr += c;
}
else
{
part1 += c;
}
}
part1 = new String(part1.Reverse().ToArray());
int number = int.Parse(new String(numberStr.Reverse().ToArray()));
String result = String.Format("{0}{1}#{2}", part1, number++, tokens[1]);
Although it looks a little bit cumbersome. Accept a Regex answer if there's one.
This will work
public static string IncNumberBeforeAt(string text)
{
int lastAt = text.LastIndexOf('#');
if (lastAt != -1)
{
int pos = lastAt - 1;
string num = "";
while (text[pos] >= '0' && text[pos] <= '9')
{
num = text[pos] + num;
pos--;
if (pos < 0)
break;
}
int numInc = int.Parse(num) + 1;
return text.Replace(num.ToString() + "#", numInc.ToString() + "#");
}
else
{
return text;
}
}
test
IncNumberBeforeAt("awesome1#email.com"); // => returns awesome2#email.com
IncNumberBeforeAt("awesome234#email.com"); // => returns awesome235#email.com
IncNumberBeforeAt("email.com"); // => returns email.com
IncNumberBeforeAt("5#email.com"); // => returns 6#email.com
You will have to keep track of your original e-mail address:
e.g.
string originalEmail = "test#gmail.com";
var parts = originalEmail.Split('#');
txtEmail.Text = string.Format("{0}{1}#{2}", parts[0], i++, parts[1]);

Categories

Resources