Trying to extract code in the middle of a String - c#

I am trying to extract a code from a string. The string can vary in content and size but I am using Tag words to make the extraction easier. However, I am struggling to nail a particular scenario. Here is the string:
({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}
What I need to extract is the 011 part of {MP.011}. The keyword will always be "{MP." It's just the code that will change. Also the rest of the expression can change so for example {MP.011} could be at the beginning, end or middle of the string.
I've got close using the following:
int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.LastIndexOf("}");
String result = code.Substring(pFrom, pTo - pFrom);
However, the result is 011} + {SilverPrice as it is looking for the last occurrence of }, not the next occurrence. This is where I am struggling.
Any help would be much appreciated.

You could use a regular expression to parse that:
var str = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var number = Regex.Match(str, #"{MP\.(\d+)}")
.Groups[1].Value;
Console.WriteLine(number);

int pFrom = code.IndexOf("{MP.") + "{MP.".Length;
int pTo = code.IndexOf("}", pFrom); //find index of } after start
String result = code.Substring(pFrom, pTo - pFrom);

the safest option is to use Regex with Negative and Positive Lookahead. This also matches multiple if you need it anyway.
var str3 = #"({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
var result = Regex.Matches(str3, #"(?<=\{MP\.).+?(?=\})");
foreach (Match i in result)
{
Console.WriteLine(i.Value);
}

The key is to use the .IndexOf(string text,int start) overload.
static void Main(string[] args)
{
string code = "({GoldPrice} * 0.376) + {MP.011} + {SilverPrice}";
// Step 1. Extract "MP.011"
int pFrom = code.IndexOf("{MP.");
int pTo = code.IndexOf("}", pFrom+1);
string part = code.Substring(pFrom+1, pTo-pFrom-1);
// Step 2. Extact "011"
String result = part.Substring(3);
}
or you can combine the last statements into
String result = code.Substring(pFrom+1, pTo-pFrom-1).Substring(3);

Related

How can I get the index of second comma?

//read
Console.Write("Please enter (pyramid slot number,block letter,whether or not the block should be lit): ");
string csvString = Console.ReadLine();
//location of comma
int firstComma = csvString.IndexOf(',');
int secondComma = csvString.IndexOf(',', firstComma + 1);
//extract slot number of pyramid
int slotNumber = int.Parse(csvString.Substring(0, firstComma));
string blockLetter = csvString.Substring(firstComma + 1, secondComma);
Boolean lit = Boolean.Parse(csvString.Substring(secondComma + 1));
//print
Console.WriteLine("Pyramid Slot Number: " + slotNumber);
Console.WriteLine("Block Letter: " + blockLetter);
Console.WriteLine("Lit: " + lit);
I tried to input like "5,M,true". However output for Block Letter is "M,t". If I try to input 15 instead of 5, then it gives "M,tr". In the end, I want to get only one letter. I'll use char after I figure this problem out.
Edit:
char blockLetter = char.Parse(csvString.Substring(firstComma + 1, 1));
I used this thank you!
The first parameter of String.Substring is the start index, the second parameter is not the end index but the length. So you need to calculate it:
int firstComma = csvString.IndexOf(',');
int startIndex = firstComma + 1;
int secondComma = csvString.IndexOf(',', startIndex);
int length = secondComma - startIndex;
string blockLetter = csvString.Substring(startIndex, length);
An easier way is to use String.Split to get a string[] with all tokens delimited by comma:
string[] allSlots = csvString.Split(',');
// first token is in allSlots[0] and second in allSlots[1]
As I understand, based on code provided, you want the values delimited by commas. If I guessed correctly, then better use String.Split method.
If your CSV file contains the data you anyway read, you could just split the string on comma and then extract individual fields by indices. Here is an example:
var csvEntry = "5,M,true";
var entryData = csvEntry.Split(',');
var slotNumber = int.Parse(entryData[0]);
var blockLetter = entryData[1];
var lit = bool.Parse(entryData[2]);
Console.WriteLine($"Pyramid Slot Number: {slotNumber}");
Console.WriteLine($"Block Letter: {blockLetter}");
Console.WriteLine($"Lit: {lit}");

Errors with splitting string

I'm quite new to programming and I'm trying to split the string below to just 36.20C but I keep getting ArgumentOutOfRangeWasUnhandled. why?
private void button1_Click(object sender, EventArgs e)
{
string inStr = "Temperature:36.20C";
int indexOfSpace = inStr.IndexOf(':');
//stores the address of the space
int indexOfC = inStr.IndexOf("C");
//stores the address of char C
string Temp = inStr.Substring(indexOfSpace + 1, indexOfC);
textBox1.Text = Temp;
}
expected output : 36.20C
The second argument of String.Substring is the length but you have provided the end index. You need to subtract them:
string Temp = inStr.Substring(++indexOfSpace, indexOfC - indexOfSpace);
You could also remove the C from the end:
string Temp = inStr.Substring(++indexOfSpace).TrimEnd('C'); // using the overload that takes the rest
As an aside, you should use the overload of IndexOf with the start-index in this case:
int indexOfC = inStr.IndexOf('C', indexOfSpace);
Here is an easier approach:
Temp = inStr.Split(':').Last().TrimEnd('C');
If you check the documentation for Substring, you'll see that the second parameter is the length, not the end position. However, there is an overload for SubString that only needs the start position and it'll return the string from there to the end of the string:
int indexOfSpace = inStr.IndexOf(':');
string Temp = inStr.Substring(indexOfSpace + 1);
var arrayStr = inStr.split(':');
textbox1.text = arrayStr[1];
you can do it like
string Temp = inStr.Substring(indexOfSpace + 1, inStr.Length - indexOfSpace - 1)
Second parameter of Substring is length. You must update as following:
string Temp = inStr.Substring(indexOfSpace + 1, indexOfC - indexOfSpace);
Just use string.Split().
string[] temp = inStr.Split(':');
textbox1.Text = temp[1];
// temp[1] returns "36.20C"
// temp[0] returns "Temperature"
string temperature = "temperature:32.25C";
Console.WriteLine(temp.Substring(temp.Trim().IndexOf(':')+1));
In substring, 2nd argument is length and if u do not specify any argument substring processes till the end of string.

Extract text with random numbers inside using C#

In C#, if I have a long string that will always contains somewhere a format such as W##S##Q## where # can be any number, how can I get that sequence of W##S##Q## extracted from the string. Bare in mind that the string may have more before or after but I am only interested in that sequence.
Regards.
Wobbles comment is correct, a regular expression such as #"W\d{2}S\d{2}Q\d{2}" will do what you need. \d matches any any decimal digit and the {2} afterwards tells it to match exactly twice.
This fiddle gives an example of how you would extract the string you want from a longer string.
Wobbles is right, Regular Expressions are the best way to do it generally. For your specific example, if you know in advance that the W,S,Q portions are always going to be in the same place you could use:
string testString = "WSomethingW01S02Q03SomethingElse";
bool TheRightString = false;
string WNumString = string.Empty;
string SNumString = string.Empty;
string QNumString = string.Empty;
int StartPosition = 0;
do
{
StartPosition = testString.IndexOf('W', StartPosition);
WNumString = testString.Substring(StartPosition, 3);
SNumString = testString.Substring(StartPosition + 3, 3);
QNumString = testString.Substring(StartPosition + 6, 3);
StartPosition += 1;
if (SNumString.StartsWith("S") && QNumString.StartsWith("Q"))
TheRightString = true;
} while (TheRightString == false);
Console.WriteLine(WNumString + SNumString + QNumString);
Console.ReadKey();

Substring from specific sign to sign

I have a list of strings in format like this:
Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp
I need only the part from comma sign to the first dot sign.
For example above it should return this string: IScadaManualOverrideService
Anyone has an idea how can I do this and get substrings if I have list of strings like first one?
from comma sign to the first dot sign
You mean from dot to comma?
You can split the string by comma first, then split by dot and take the last:
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string result = text.Split(',')[0].Split('.').Last(); // IScadaManualOverrideService
Splitting strings is not what can be called effective solution. Sorry can't just pass nearby.
So here is another one
string text = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', end) + 1;
var result = text.Substring(start, end - start);
Proof woof woof.
Bullet-proof version (ugly)
string text = "IScadaManualOverrideService";
//string text = "Services.IScadaManualOverrideService";
//string text = "IScadaManualOverrideService,";
//string text = "";
var end = text.IndexOf(',');
var start = text.LastIndexOf('.', (end == -1 ? text.Length - 1 : end)) + 1;
var result = text.Substring(start, (end == -1 ? text.Length : end) - start);
Insert this if hacker attack is expected
if(text == null)
return "Stupid hacker, die!";
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string s1 = s.Substring(0, s.IndexOf(","));
string s2 = s1.Substring(s1.LastIndexOf(".") + 1);
string input = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
int commaIndex = input.IndexOf(',');
string remainder = input.Substring(0, commaIndex);
int dotIndex = remainder.LastIndexOf('.');
string output = remainder.Substring(dotIndex + 1);
This can be written a lot shorter, but for the explanation i think this is more clear
sampleString.Split(new []{','})[0].Split(new []{'.'}).Last()
string s = "Web.WebClient.Areas.Scada.Services.IScadaManualOverrideService,Web.WebClient.TDMSWebApp";
string subStr = new string(s.TakeWhile(c => c != ',').ToArray());
string last = new string(subStr.Reverse().TakeWhile(c => c != '.').Reverse().ToArray());
Console.WriteLine(last); // output: IScadaManualOverrideService

Adding a '-' to my string in C#

I Have a string in the form "123456789".
While displaying it on the screen I want to show it as 123-456-789.
Please let me knwo how to add the "-" for every 3 numbers.
Thanks in Advance.
You can use string.Substring:
s = s.Substring(0, 3) + "-" + s.Substring(3, 3) + "-" + s.Substring(6, 3);
or a regular expression (ideone):
s = Regex.Replace(s, #"\d{3}(?=\d)", "$0-");
I'll go ahead and give the Regex based solution:
string rawNumber = "123456789";
var formattedNumber = Regex.Replace(rawNumber, #"(\d{3}(?!$))", "$1-");
That regex breaks down as follows:
( // Group the whole pattern so we can get its value in the call to Regex.Replace()
\d // This is a digit
{3} // match the previous pattern 3 times
(?!$) // This weird looking thing means "match anywhere EXCEPT the end of the string"
)
The "$1-" replacement string means that whenever a match for the above pattern is found, replace it with the same thing (the $1 part), followed by a -. So in "123456789", it would match 123 and 456, but not 789 because it's at the end of the string. It then replaces them with 123- and 456-, giving the final result 123-456-789.
You can use for loop also if the string length is not fixed to 9 digits as follows
string textnumber = "123456789"; // textnumber = "123456789012346" also it will work
string finaltext = textnumber[0]+ "";
for (int i = 1; i < textnumber.Length; i++)
{
if ((i + 1) % 3 == 0)
{
finaltext = finaltext + textnumber[i] + "-";
}
else
{
finaltext = finaltext + textnumber[i];
}
}
finaltext = finaltext.Remove(finaltext.Length - 1);

Categories