How can I get the index of second comma? - c#

//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}");

Related

Trying to extract code in the middle of a String

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);

how i can get the string after specific character in my case :?

str="Brand : TROLLBEADS";
int length = str.Length;
length = length - 6;
str = str.Substring(6, length);
i want to display "TROLLBEADS"
and want to discard other remaining string
You can split the string using : delimiter if it is fixed
var result = str.Split(':')[1].Trim();
or if your string can have multiple : in that case
var result = str.Substring(str.IndexOf(":") + 1).Trim();
Split is nice, but a bit too much. You can just specify the start position for substring.
string str="Brand : TROLLBEADS";
string val = str.Substring(str.IndexOf(":") + 1);
Console.WriteLine(val);

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.

C# Search for a word occurances within a string

How can I search for a word within a string ?
I have one text box which the user insert a string and another on with with text just some random text.
Are there any alterative ways of doing this besides using regex and IndexOf? Like using a for loop and checking the length and character in the word.
This is what I tried so far
int i = 0;
int count = 0;
input2.Trim();
while ((i = input2.IndexOf(input1, i)) != -1)
{
i = i + input1.Length;
count++;
}
MessageBox.Show(count.ToString() + " Matches Found");
Looks like you want to get the Count of search string in the text. You can try the following.
string searchString = "TEST";
string completeText = "Some sentence TEST with other words incluing TEST";
int count = completeText.Split(new string[]{"TEST"},StringSplitOptions.None)
.Count() - 1;
MessageBox.Show(count.ToString() + " Matches Found");
Use a regex to match the number of occurances,
string test = "THE DOG WENT TO TOWN DOG";
int j = Regex.Matches(test, "DOG").Cast<Match>().Count();

Manipulating String in C#

I have a code in C# and have to print a label with the name of the seller, but i have a problem.
Every line in the label comport 20 letters and i have 2 lines to put this name.
I need to arrange the name of the seller in the 2 lines, without cut words.
For example - Name: JOSE MAURICIO BERTOLOTO MENDES
Line1: JOSE MAURICIO
Line2: BERTOLOTO MENDES
someone know how i do this?
Thanks
EDIT: Based in the answers, i implemente this code:
string[] SellerPrint = Seller.Split(' ');
Line1 = "";
Line2 = "";
foreach (string name in SellerPrint )
{
if (Line1.Length <= 20)
{
if ((Line1 + name).Length <= 20)
Line1 += (Line1.Length == 0) ? name : " " + name;
else
break;
}
}
Line2 = (Seller.Replace(Line1, "").Length <= 20) ? Seller.Replace(Line1+ " ", "") : Seller.Replace(Line1+ " ", "").Remove(20);
Thanks for the help!
You could simply split the string into words using string.Split() and then add to each as long it small enough to add to the line.
I also wouldn't use the character count but use Graphics.MeasureString() instead.
You can split the full name in to it's individual parts.
var names = fullname.Split(' ');
Which will give you a string[]. From there you can do the math by looking at length of each string.
The idea is that you want to append all parts of the name until you will reach or exceed your 20 character limit on the next token. When that happens, append a new line with that token and continue appending until you hit the character limit once again.
Here is a quick example:
public static string FormatName(string name)
{
const int MaxLength = 20;
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (name.Length <= MaxLength)
return name;
string[] tokens = name.Split(' ');
if (tokens.Length == 0)
return name; //hyphen the name?
StringBuilder sb = new StringBuilder(name.Length);
int len = 0;
foreach (string token in tokens)
{
if (token.Length + len < MaxLength)
{
sb.Append(token + " ");
len += token.Length;
}
else
{
sb.Append(Environment.NewLine + token + " ");
len = 0;
}
}
return sb.ToString();
}
Note: I left the case open for when a section of the name, without spaces, is longer than 20 characters. Also, this example will continue on to the Nth line, if the name won't fit onto two lines.
Here is the logic.
Use String.split to split the name into an array. Iterate over the strings in the array, concat them into a line, while the line is less than 20 characters. A recursive function would be a good idea! When you are greater than two lines, drop the rest of the names that put it over.
I'm not sure but I think you can use a special character: '\n' (without the quotes)
Its basiclly stands for new line. So for example : JOSE MAURICIO BERTOLOTO MENDES will become JOSE MAURICIO \n BERTOLOTO MENDES.

Categories