Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i have two string variables named X and Y respectively. What i want is to replace the X string from the Y variable. I'm using the command string.replace put nothing comes through.
the code i'm using is shown below,
thanks
Stavros Afxentis
string Y= string.Empty;
string X= string.Empty;
Y= get_y_value(...); // my method to get string y
X= get_x_vale(...); // my method to get string X
Y= Y.Replace(X, "");
// i also used Y= Y.Replace(X.ToString(), "");
// but the result is the same
Replace is used to change a "word" inside another string. Like so:
string badString = "Can I has the code";
string goodString = badString.Replace("has", "have");
Your biggest problem is that both strings are Empty.
The code should work flawlessly it will remove the string X because you are replacing it with 0 length string, there might be 2 reasons why this isn't working,
1) X not found in Y
2) You didn't print or show the updated Y
finally i used the code below, where i converted the string to char array and i removed the unwanted text.. pseudocode below:
int i=0;
while ((i<Y.Length) && (counter<1))
{
//ignore part of the string
// and save the position of the char array i want
}
while (poss<Y.Length)
{
new_ch[poss] = ch[poss] //save the array to new char array
}
string y_new = new string(new_ch);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Code:
namespace DriversLicenceExam
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
LoadKey();
LoadAnswer();
}
private void LoadKey()
{
try
{
const int AnsLgth = 20;
string[] Answers = new string[AnsLgth];
int index = 0;
System.IO.StreamReader inputFile;
inputFile = File.OpenText("DRIVERKEY.txt");
{
Answers[index] = (inputFile.ReadLine());
index++;
}
inputFile.Close();
for (int i = 0; i <= Answers.Length; i++)
{
string value = Answers[i];
listBox1.Items.Add(value);
}
}
catch (Exception)
{
throw;
}
}
I keep getting an error stating 'Value cannot be null. Parameter name; item'
I am relatively new to coding and not sure what this means. Any help or input is appreciated.
The goal of this program is to insert an answer key file, turn it into an array, output it into a listbox, then do the same with answer files, grade the answer files that are submitted by "students" by crossreferencing them with the answer key array, then output the incorrect answers into another listbox.
This is only the first method where I am supposed to input the answer key file then turn it into an array and display it in a listbox.
The answer key text file looks like this:
B
D
A
A
C
A
B
A
C
D
B
C
D
A
D
C
C
B
D
A
You're reading one line from the file into the first element of the array. So the rest of the elements are null. Then you're trying to add all of the elements to a UI control:
listBox1.Items.Add(value);
It's accepting the first non-null value but the remaining 19 null values are problematic.
I suspect you meant for this to be a loop:
{
Answers[index] = (inputFile.ReadLine());
index++;
}
But you forgot... the loop. Perhaps something like this:
var line = "";
while ((line = inputFile.ReadLine()) != null)
{
Answers[index] = line;
index++;
}
Though even then, there's really no guarantee that the number of lines will always equal the hard-coded array size. If there are fewer, the same error will occur. If there are more, a different error will occur.
This is an example where a more dynamic data structure, such as a List<>, would be helpful. Something like this:
var Answers = new List<string>();
Then the collection will automatically grow to only the size needed as you add to it. So the loop would be:
var line = "";
while ((line = inputFile.ReadLine()) != null)
{
Answers.Add(line);
}
Using a List<> is slightly different from using an array. For example, you'd use .Count instead of .Length. But overall what you have is conceptually the same. A List<> is just more dynamic than a fixed-length array.
Here
inputFile = File.OpenText("DRIVERKEY.txt");
{
Answers[index] = (inputFile.ReadLine());
index++;
}
There is no loop around the part that reads a line from the file and assigns it to the array. So only one line is read and only the first entry in the array is filled.
There are further problems further down in the code. But try to understand and fix that one first. Tip: Learn how to work with the debugger. Set breakpoints, step through the code line by line and look at the variables while the code executes.
Here is a good video tutorial on using the debugger in Visual Studio: https://www.youtube.com/watch?v=sACkw915kmg
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am new to C# but I have learned Java for a year and I found C# almost similar. I am trying to make a program where the output is like this
My
My Name
My Name Is
My Name Is Ahan
and the program I have written is this
class Program
{
static void Main(string[] args)
{
string str1 = "My Name Is Ahan";
int i = 0 , length = str1.Length;
Console.WriteLine(length);
for(; i<length; i++ )
{
char ch = str1[i];
if (ch == ' ')
{
int catchnum = str1.IndexOf(ch);
string displayValue = str1.Substring(0, catchnum);
Console.WriteLine(displayValue);
}
else;
}
Console.ReadLine();
}
}
Something like this?
static void Main(string[] args)
{
string str1 = "My Name Is Ahan";
string[] words = str1.Split(' ');
for (int i=0;i<words.Length;i++)
{
var selectedWords = words.Take(i + 1);
Console.Write($"{string.Join(" ", selectedWords)} ");
}
}
I think your problem is here:
int catchnum = str1.IndexOf(ch);
Within the loop you're always finding the index of the first space. You already have the index of the current space when you find it, so you could just do:
if (ch == ' ')
{
string displayValue = str1.Substring(0, i);
Console.WriteLine(displayValue);
}
I would also note that C# and Java are extremely similar for these basic operations - the same code would behave identically in Java with only minor syntax differences. Certainly the code could be simpler by using some basic library functions (like string.Split and Linq) that would be different between the two platforms, but that's not the issue here.
In other words, your errors aren't due to translation between Java and C# - they're basic logic errors that would have manifested in any programming language.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm new in C#. I want to show my return values from my MyApp method.
public int MyApp(string strFirst, string strSecond)
{
if (strFirst.Equals(strSecond))
{
return 0;
}
for (int i = 0; i < strFirst.Length; i++)
{
string temp = strFirst.Substring(0, strFirst.Length - 1);
temp = strFirst[strFirst.Length - 1] + temp;
strFirst = temp;
if (strFirst.Equals(strSecond))
{
return i + 1;
}
}
return -1;
}
If you do not call Console.WriteLine(), nothing will be printed to the console.
So do:
Console.WriteLine(calc.MyApp("try", "yrt"));
And we usually name methods with descriptive verbs - so your MyApp should become Calculate.
Whereas classes should be named with nouns - so your Calculate should become MyApp.
That way, your code is more expressive:
var app = new MyApp();
Console.WriteLine(app.Calculate("try", "yrt"));
you can use this:
class Program
{
static void Main(string[] args)
{
Calculate calc = new Calculate();
int result = calc.MyApp("try", "yrt");
Console.WriteLine(result);
}
}
The issue is on this line:
calc.MyApp("try", "yrt");
You are calling your MyApp method, but you are not storing or using the result.
Storing the result in a variable is useful if you intend to use the result for other things:
//Store the result
var result = calc.MyApp("try", "yrt");
//Display the result
Console.Writeline(result);
You can also just pass the expression (the call to method MyApp) as an argument to the Writeline method:
Console.Writeline(calc.MyApp("try", "yrt"));
The runtime will execute the call to your method and use the result as the argument of the call to method Writeline.
Either way works. I personally would recommend using a variable if you are just getting started. Inline calls save space and can be more performant but they also make debugging harder.
If you use Console.WriteLine() and it always returns -1 where it shouldn't your problem lies with the code in the MyApp() Method.
The real problem is that you are rotating your first string and not turning it around.
So, if your first string is "hello" and your second string is "olleh" - for each iteration you will get the following for your first string:
ohell
lohel
llohe
elloh
hello
You will never get "olleh"
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm very new to c#. I created a forms. A richtextbox and a button in it.
I have a list of operators: Sum, Subtract,Multi,Div.I want to run a small richtextbox test. For example,in the richtextbox I write a text (eg. Sum(1,2)) and then click the button. A return result(eg.3) prints in the richtextbox.
My idea is to use string contains
foreach( var element in operatorlist)
{
string text=richtextbox.text;
if( text.contains(element)== true)
{
element(parameter1,parameter2);//something like this
}
}
I met two questions right row.
My first question is how to get the mathematical operation from the richtextbox text. Is there a better way than mine?
My second question is once we know the operator,how to allocate the two parameters in the richtextbox to the operator.
I'm not asking for coding, I'm just looking for ideas. If you have a good idea and wish to share.
You can evaluate an expression using the DataTable.Compute function:
int p1 = 1 ; string s1 = p1.ToString() ;
int p2 = 2 ; string s2 = p2.ToString() ;
int p3 = 3 ; string s3 = p3.ToString() ;
// Compute (p1+p2)*p3 ==> 9
int result = new DataTable().Compute( "("+s1+"+"+s2+")*"+s3+")","") ;
or directly:
string expression = "(1+2)*3" ;
int result = new DataTable().Compute(expression,"") ;
I think this comes down to personal style. Your way will definitely work, so good on you for that. The way I would do it is to create a Dictionary of strings to an enum. So for example, said dictionary and enum might look like this:
enum Operator { Addition = 0, Subtraction = 1, Multiplication = 2, Division = 3, etc};
var operatorDictionary = new Dictionary<string, Operator>()
{
{"Addition", Operator.Addition},
{"Subtraction", Operator.Subtraction},
etc...
};
Then to get the value you would just do
Operator operation;
operatorDictionary.TryGetValue(string operationString, out operation);
and you would have to then build some code that switches through the Operators and performs the correct operation. There is even a way of converting a string to an enum, so that would work as well.
It looks like the parameters are in a consistent format, so you would just make a simple method that splits by parenthesis and the comma, and returns the strings that it found.
Let me know if you need anything explained more.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The question is on C#.
I have a string "value1=1234;value2=2345;value3=3456;value4= ..."
What is the best way to retrieve the values?
I thought about String.Split(";") but I don't know how to retrieve the values only. The result I get includes the prefix I don't want.
I only want the values of "1234", "2345", "3456"... nothing else, and them put them into a list of strings.
How do I solve this? Thanks.
If the format is always fixed, you can do it fairly easily via LINQ:
List<string> values = theString.Split(';').Select(s => s.Split('=')[1]).ToList();
Note that you may want to use RemoveEmptyEntries if your input string ends in a semi-colon:
List<string> values = theString
.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=')[1]).ToList();
This would prevent an exception from occuring within the Select. If the input doesn't end in a semi-colon, however, this wouldn't be necessary.
var text = "value1=1234;value2=2345;value3=3456;value4= ...";
var pieces = text.Split('=');
var values = new Dictionary<string,string>();
for(int index = 0; index < pieces.Length; index += 2)
{
values.Add(pieces[index], pieces[index + 1]);
}
This will give you a dictionary of the pairs where the key is the left-hand side of the '=' and the value is the string representation of the value, which allows your to do:
var value1 = values["value1"];
var value2 = values["value2"];