How to convert String to One Int - c#

following problem in C# (working in VS Community 2015):
First off, i fairly new to C#, so excuse me if that question would be an easy fix.
I have a contact sensor giving me a string of numbers (length measurement). I read them with the SystemPort Methods and cut them down to the numbers that i need with substring (as the beginning of the string, the "SR00002" is useless to me).
In the end i end up with a string like : "000.3422" or "012.2345". Now i want to convert that string to one solid int-variable that i can work with, meaning subtract values from and such.
Bsp: I want to calculate 012.234 - 000.3422 (or , instead of . but i could change that beforehand)
I already tried Parse and ConvertToInt (while iterating through the string) but the endresult is always a string.
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,");
string b2 = b1[1].Substring(1);
foreach (char c in b2)
{
Convert.ToInt32(c);
}
textBox2.Text = b2 + b2.GetType();
I know that when b2 will be int it can not be printed in the Textbox but ill take care of that later.
When everything is converted accordingly, ill outsource the conversion to its own method =)
The GetType is just for testing and as said shows only System.String (which i dont want). Help would be much appreaciated. I also browsed the searchfunction and google but couldnt find anything of help. I wish any possible helpers a nice day, mfg Chris.

use the int.Parse
int.Parse("123")

You need to assign the converted values to a new variable or array that takes int or other numeric values that you want.
int[] numbers = new int[b1.length];
for(int i = 0; i < b2.length; i++)
{
numbers[i] = Convert.ToInt32(b2[i]);
}

Related

Parsing string as int with "Model.x" property in for loop remains in string format

I have a simple form that accepts a number from a radio button selection (1-5) of 11 questions and posts the values into a database as varchar(10) data. I intend to send the user to a result page that lists the sum of these scores through a simple for loop, but when I try parsing the data to integer format, it simply results in zero due to error parsing. Here's an example of my code:
// Q1 - Q11 are the questions in my Db, using Model property
int sum = 0;
int temp = 0;
String question;
for (int i = 11; i >= 1; i--)
{
question = "Model.Q" + i.ToString();
temp = int.Parse(question);
sum += temp;
}
return sum;
What's strange is that if I parse them individually, such as writing:
Int32.TryParse(Model.Q5, out temp);
I am able to parse the data just fine. My console shows that the loop keeps the question variable as "Model.Qx" with quotations, ultimately resulting in 0 for the sum. I have also tried using Int32.TryParse(); for that as well and it resulted in no difference, besides handling the error.
Can a string simply not be parsed if it contains punctuation in concatenation with the i variable, or am I missing something else here? I want to avoid parsing each question individually, as it looks rather ugly in code.
Thanks in advance.
You problem is that you're trying to access a variable by using a string with the same name. This won't work, in the same way that the name gitgecko is not you.
If your model has got a number of properties with similar names, you could write a function to switch between them:
object GetQ(int number)
{
switch(number)
{
case 1: return Model.Q1;
case 2: return Model.Q2;
// etc...
}
}
Or you could change your model to store these variables in an array or list, or whatever is appropriate.
For example, if you've currently got:
class Model
{
string Q1;
string Q2:
// repeated 11 times
You could have:
class Model
{
string[] Q = new string[11];
}
which gives you the ability to do Model.Q[x]

How to reverse string in C# [duplicate]

I didn't get the problem - I was trying to do a simple action:
for(i = x.Length-1, j = 0 ; i >= 0 ; i--, j++)
{
backx[j] = x[i];
}
Both are declared:
String x;
String backx;
What is the problem ? It says the error in the title...
If there is a problem - is there another way to do that?
The result (As the name 'backx' hints) is that backx will contain the string X backwards.
P.S. x is not empty - it contains a substring from another string.
Strings are immutable: you can retrieve the character at a certain position, but you cannot change the character to a new one directly.
Instead you'll have to build a new string with the change. There are several ways to do this, but StringBuilder does the job in a similar fashion to what you already have:
StringBuilder sb = new StringBuilder(backx);
sb[j] = x[i];
backx = sb.ToString();
EDIT: If you take a look at the string public facing API, you'll see this indexer:
public char this[int index] { get; }
This shows that you can "get" a value, but because no "set" is available, you cannot assign values to that indexer.
EDITx2: If you're looking for a way to reverse a string, there are a few different ways, but here's one example with an explanation as to how it works: http://www.dotnetperls.com/reverse-string
String is immutable in .NET - this is why you get the error.
You can get a reverse string with LINQ:
string x = "abcd";
string backx = new string(x.Reverse().ToArray());
Console.WriteLine(backx); // output: "dcba"
String are immuatable. You have convert to Char Array and then you would be able to modify.
Or you can use StringBuilder.
for example
char[] wordArray = word.ToCharArray();
In C# strings are immutable. You cannot "set" Xth character to whatever you want. If yo uwant to construct a new string, or be able to "edit" a string, use i.e. StringBuilder class.
Strings are immutable in C#. You can read more about it here: http://msdn.microsoft.com/en-us/library/362314fe.aspx
Both the variables you have are string while you are treating them as if they were arrays (well, they are). Of course it is a valid statement to access characters from a string through this mechanism, you cannot really assign it that way.
Since you are trying to reverse a string, do take a look at this post. It has lot of information.
public static string ReverseName( string theName)
{
string revName = string.Empty;
foreach (char a in theName)
{
revName = a + revName;
}
return revName;
}
This is simple and does not involve arrays directly.
The code below simply swaps the index of each char in the string which enables you to only have to iterate half way through the original string which is pretty efficient if you're dealing with a lot of characters. The result is the original string reversed. I tested this with a string consisting of 100 characters and it executed in 0.0000021 seconds.
private string ReverseString(string testString)
{
int j = testString.Length - 1;
char[] charArray = new char[testString.Length];
for (int i = 0; i <= j; i++)
{
if (i != j)
{
charArray[i] = testString[j];
charArray[j] = testString[i];
}
j--;
}
return new string(charArray);
}
In case you need to replace e.g. index 2 in string use this (it is ugly, but working and is easily maintainbable)
V1 - you know what you want to put their. Here you saying in pseudocode string[2] = 'R';
row3String.Replace(row3String[2], 'R');
V2 - you need to put their char R or char Y. Here string[2] = 'R' if was 'Y' or if was not stay 'Y' (this one line if needs some form of else)
row3String.Replace(row3String[2], row3String[2].Equals('Y') ? 'R' : 'Y');

Searching a string array without built in methods

If anyone can help out there, I'll be tremendously grateful.
Essentially I am working on a homework project where, for part of it, I need to search an array. The array, I currently have as a String type, but is essentially a collection of dates. (In the format 05/06/2014)
I am just about at my wits end trying to find a way to allow the user to search this array, in particular that doesn't use built in methods like array.binarysearch etc.
I tried to implement a binary search but that didn't seem to work, I can provide code if you wish to see where I'm probably going wrong. But is there perhaps a better search I should use for this string type, or should I be converting the string array into a different type?
If anyone can help I would greatly appreciated, I'm not necessarily asking for anyone to do my work for me I'd just be thrilled if someone could bump me in the right direction, as this problem has been doing my nut in. Thanks!
Current Binary Search Code:
public static void BinarySearch(string[] dateArray, string searchTerm)
{
int first = 0;
int last = dateArray.Length - 1;
int position = -1;
bool found = false;
int compCount = 0;
while (found != true && first <= last)
{
int middle = (first + last) / 2;
int comparisonSTR = string.Compare(dateArray[middle], searchTerm);
if (dateArray[middle] == searchTerm)
{
found = true;
position = middle;
compCount++;
Console.WriteLine("Your search has been found after " + compCount + "comparisons.");
}
else if (comparisonSTR > 0)
{
last = middle;
compCount++;
}
else
{
first = middle;
compCount++;
}
}
}
For an educational response, your binary search is correct*, if not very clean - like #Alex said, you only have to make sure you're comparing them as DateTimes. The problem is with the line
int comparisonSTR = string.Compare(dateArray[middle], searchTerm);
because the "string class" doesn't know what a date is so it can't really give you a datetime comparison when you're trying to search for dates. It can only give you a comparison on if one term comes alphabetically before, equal, or after another term.
Instead, if you convert them to DateTimes and use the comparer specific for DateTimes, then you should get back a comparison that you can use for binary search. You can either convert them to DateTime in-line
int comparisonSTR = DateTime.Compare(Convert.ToDateTime(searchTerm), Convert.ToDateTime(dateArray[middle]));
or convert them outside of the loop as the first thing you do in your method to make it a little easier to read
DateTime[] dates = Array.ConvertAll(dateArray, Convert.ToDateTime);
DateTime searchDate = Convert.ToDateTime(searchTerm);
while (found != true && first <= last)
{
int middle = (first + last) / 2;
int comparison = DateTime.Compare(searchDate, dates[middle]);
Other than that, you're pretty much set. You might have already solved this by now, so in that case I'm just posting it in part to explain why the string.Compare didn't work for you to convert dates in this case.
Edit: Make sure to test your edge cases (e.g. searching for not only the middle, but also the first and last elements for varying array sizes), because I suspect that your binary search may not be entirely correct on second review.

Arrays Windows Forms Index was outside the bounds

there are a couple of these questions asked, but mine primarily involves Windows Forms, which there are few, although if there is an answer, a relatively well explained one without complicated jargon please let me know so I can learn from it.
Cutting to the chase: I want to read some data from a txt file into an array and then display it into some radio buttons. But for here I have simplified it and put them into a messagebox.
private void Game1_Load(object sender, EventArgs e)
{
const int iGAME = 4;
string[] sQuestions = new string[iGAME];
int iNum;
using (StreamReader sr = new StreamReader("questions.txt"))
{
for (iNum = 0; iNum < iGAME; iNum++)
{
MessageBox.Show(sQuestions[iGAME]);
}
}
The problem here is that the system tells me that the index exceeds the bounds. Now I have checked the txt file and there is definitely 4 pieces of information to apply to an array.
You're using the wrong index for the array. You're passing iGAME (a constant set to 4) when you should be using iNum (a variable between 0-3). Given that the upper-bound for the index is 3, the 4 will cause the ArrayIndexOutOfBoundsException.
Also, tip: C# is not C, so you don't need to use separate constants to denote the length of an array, also convention in C-style languages is to use just i as an index variable, and it avoids confusion between iGAME and iNum which has befallen you. Finally, avoid including the type-name in a variable's name, you don't need it anymore, this isn't the 1980s with Hungarian notation. You can rewrite your code to be more maintainable as:
String[] questions = new String[ 4 ];
for(int i=0; i<questions.Length; i++) {
...
}
Or just use this:
String[] questions = File.ReadAllLines( fileName );
foreach(String question in questions) MessageBox.Show( question );
I dont get what you want but first
MessageBox.Show(sQuestions[iGAME]) is wrong
change it to
MessageBox.Show(sQuestions[iNum ]);
I have managed to fix my code, to those that are doing a similar sort of thing to me here is my fix, hope it helps you:
int i;
using (StreamReader sr = new StreamReader("questions.txt"))
{
for (i = 0; i < Questions.GetLength(0); i++)
{
MessageBox.Show(Questions[i] = Convert.ToString(sr.ReadLine()));`
What I did here is state the loop variable i, using StreamReader to read the TXT file (don't forget to add using System.IO; at the top of the page. I then created a for loop so that it saves time by assigning each array with data. I then decided to show the results in a messagebox for simplicity by stating the Questions with the array counter [i] and then converted it to a string so it could be read in the box as before hand it was just blank.
Hopefully that little friendly walkthrough helps you solve your issue.

Conversion vb6 to c#

I am trying to convert some vb6 code to c# and I am struggling a bit.
I have looked at this page below and others similar, but am still stumped.
Why use hex?
vb6 code below:
Dim Cal As String
Cal = vbNull
For i = 1 To 8
Cal = Cal + Hex(Xor1 Xor Xor2)
Next i
This is my c# code - it still has some errors.
string Cal = null;
int Xor1 = 0;
int Xor2 = 0;
for (i = 1; i <= 8; i++)
{
Cal = Cal + Convert.Hex(Xor1 ^ Xor2);
}
The errors are:
Cal = Cal + Convert.Hex(Xor1 ^ Xor2 ^ 6);
Any advice as to why I cant get the hex to convert would be appreciated.
I suspect its my lack of understanding the .Hex on line 3 above and the "&H" on line 1/2 above.
Note: This answer was written at a point where the lines Xor1 = CDec("&H" + Mid(SN1, i, 1))
and Xor1 = Convert.ToDecimal("&H" + SN1.Substring(i, 1)); were still present in the question.
What's the &H?
In Visual Basic (old VB6 and also VB.NET), hexadecimal constants can be used by prefixing them with &H. E.g., myValue = &H20 would assign the value 32 to the variable myValue. Due to this convention, the conversion functions of VB6 also accepted this notation. For example, CInt("20") returned the integer 20, and CInt("&H20") returned the integer 32.
Your code example uses CDec to convert the value to the data type Decimal (actually, to the Decimal subtype of Variant) and then assigns the result to an integer, causing an implicit conversion. This is actually not necessary, using CInt would be correct. Apparently, the VB6 code was written by someone who did not understand that (a) the Decimal data type and (b) representing a number in decimal notation are two completely different things.
So, how do I convert between strings in hexadecimal notation and number data types in C#?
To convert a hexadecimal string into a number use
int number = Convert.ToInt32(hex, 16); // use this instead of Convert.ToDecimal
In C#, there's no need to pad the value with "&H" in the beginning. The second parameter,16, tells the conversion function that the value is in base 16 (i.e., hexadecimal).
On the other hand, to convert a number into its hex representation, use
string hex = number.ToString("X"); // use this instead of Convert.ToHex
What you are using, Convert.ToDecimal, does something completely different: It converts a value into the decimal data type, which is a special data type used for floating-point numbers with decimal precision. That's not what you need. Your other method, Convert.Hex simply does not exist.

Categories