So I have a very simple bit of code
public static string[] config = File.ReadAllLines(Environment.CurrentDirectory.ToString() + "\\documents\\config.json");
public static void Start()
{
Console.WriteLine(config[4]);
Console.ReadKey();
}
This properly displays the 5th item in the array, which is "0x00=jU0UrZBkqPXfp8MsMoILSRylevQGaUmJRnpFbfUvcGs=7lvpCgtyWl0 : crypt_wallet". I only want the first part of the string, so "0x00=jU0UrZBkqPXfp8MsMoILSRylevQGaUmJRnpFbfUvcGs=7lvpCgtyWl0".
When I use Console.WriteLine(config[4].split(null); or anything else in the split arguments, I just get back System.String[].
How would I fix that so it properly displays the answer?
Should rather be like below since you will have to choose the element to print since Split() returns a string[]
Console.WriteLine(config[4].Split(':')[0]);
Not sure what you mean by the "the first part of the string". But you can achieve this by using .Substring().
If you know that the beginning will always be a fixed length, you can do:
config[4].Substring(0, 4);
If you know the value will be followed by a certain character (like the "=" for an example:
config[4].Substring(0, config[4].IndexOf("="));
Related
Hi i'm currently using Thread.Sleep(200); in between text for it to look like old pokemon game with the text not appearing all at once but going a bit laggy word for word like this
Console.Write("help"); Thread.Sleep(200); Console.Write("me");
And i'm wondering if you can name/shorten the Thread.Sleep(200) to something like Ts200. (I mean to text). So it's not much clutter.
So it would be something like this with a string.
string Ts200
Ts200 = Thread.Sleep(200)
Console.Write("help"); Ts200; Console.Write("me")
But it's not working.
I get this error:
cannot implicitly convert type void to string
a simple way to do this would be to split the strings into arrays on spaces, then loop over them.
using System;
using System.Threading;
public static void slowType(string fullSentence, int millis_pause)
{
string[] words = fullSentence.Split(' ');
foreach(string s in words)
{
Console.Out.Write(s);
Thread.Sleep(millis_pause);
//we must reintroduce the space, since we were splitting on it.
Console.Out.Write(' ');
}
//optionally ; start a new line at the end of the sentence
Console.Out.Write("\r\n");
}
usage example :
public static void Main()
{
string sentence = "i am a terribly slow typist";
slowType(sentence, 200);
}
Try lambda if you don't mind () after Ts200:
Action Ts200 = () => Thread.Sleep(200);
...
Ts200();
However, even if it's possile Ts200() is far less readable than Thread.Sleep(200), that's why don't do it.
You call the Thread.Sleep(200); on its own, it doesnt contain any value. So you cant return any value neither can you allocate it any value, except as the method parameter Thread.Sleep("Here belongs the method parameter, this method accepts an 'int' value"). The int method parameter sets for how many milli seconds you want to pause the mainthread.
Try something like this:
The main method is the entry point in your application once it gets executed. So when you start your application, you call the main method and execute it.
static void Main(string[] args)
{
string sentence = "Here you enter your sentence...";
string[] words = sentence.Split(' ');
OutputDelayedText(words);
}
The string sentence is the string variable that contains the sentence you want to ouput on the console. So we split the sentence into single words with the method .Split(' '). This splits the spring on each space ' ' and puts the single words into a string[] array. Note that you have to use in the .Split('') method these '' instead of what you are probably used to "". Thats because the method accepts a char value and those '' indicate that you just put a single char in as the method parameter.
So in the end we call the OutputDelayedText() method with our word array as method parameter.
private static void OutputDelayedText(string[] myText)
{
foreach (var word in myText)
{
Console.Write(word + " ");
Thread.Sleep(200);
}
}
Now we use a foreach loop to iterate over the array and write every single element of our array (one single word of our sentence) in one line on the console. If you are not familiar with foreach you could use either a for or while loop as well.
In generell i advice you to use Task.Delay(). Or in WinForms the Backgroundworker, those will allow you to work on different threads and if you pause those threads you dont pause your main thread. You will come across this issue later, this is used to pause any process or to execute a long task in the background to not freeze your GUI when the task is still running.
However just start with Thread.Sleep(), but keep in mind: In the art of programming are so many ways how to achieve your goal and you might stumble quite often over a better solution.
Using this, I'm trying to print a list of the contents of players.text
I know that the foreach loop will print it just fine if the Console.Writeline
is used. But I'm attempting to manipulate the data in particular ways later, and need it split using the indicated delimiter.
However, with the given code all I get is a repeated System.String[] printout.
I've done a search or two and most of what I've found has to do with one part or the other, I haven't found any information on how to use them together.
string[] playerFile = File.ReadAllLines("players.txt");
foreach (string s in playerFile)
{
//Console.WriteLine(s);
string[] playerStuff = s.Split(';');
Console.WriteLine(playerStuff);
}
Console.ReadKey();
I realize it's a simplistic question. But often, for me at least, it's missing the obvious that drives me the most crazy.
Thanks in advance.
Player;Team;POS;HR;RBI;AVG
Abreu, J;CWS;1B;30;101;0.29
Altuve, J;HOU;2B;15;66;0.313
Andrus, E;TEX;SS;7;62;0.258
Arenado, N;COL;3B;42;130;0.287
Aybar, E;LAA;SS;3;44;0.27
The above is the first few lines of the input.
Basically, I want it to look just like that, minus the semicolons. Formatting will come later.
Attempting to add a second foreach, such as was suggested below, the code looked like this:
foreach (string s in playerFile)
{
//Console.WriteLine(s);
string[] playerStuff = s.Split(';');
foreach (string player in playerStuff)
{
Console.WriteLine(player);
}
}
This resulted in EACH piece of information getting it's own line. I follow the logic of why it did that, but I'm not sure what to do about it.
For a method call to compile the compiler has to figure out what you want to do and here, in particular, there are many overloads to the Console.WriteLine method. An "overload" basically means that there are several definitions of Console.WriteLine, all taking different types of parameters.
If the compiler can find an overload that takes exactly what you're trying to pass it, in this case string[], then good, that's the overload that will be called.
If not then it will take "the next best thing", if at all possible.
Let's list all the overloads to Console.WriteLine:
WriteLine()
WriteLine(Boolean)
WriteLine(Char)
WriteLine(Char[])
WriteLine(Char[], Int32, Int32)
WriteLine(Decimal)
WriteLine(Double)
WriteLine(Int32)
WriteLine(Int64)
WriteLine(Object)
WriteLine(Single)
WriteLine(String)
WriteLine(String, Object)
WriteLine(String, Object, Object)
WriteLine(String, Object, Object, Object)
WriteLine(String, Object, Object, Object, Object)
WriteLine(String, Object[])
WriteLine(UInt32)
WriteLine(UInt64)
Now, now of these will be able to accept a string[] except one:
WriteLine(Object)
This particular overload will simply call .ToString() on whatever it is passed.
Since a string array does not have a ToString implementation that looks at the contents of the array, or anything like that, the basic System.Object.ToString() method that every type inherits is used, and this simply returns the full name of the type as a string, which is basically System.String[].
So that's why the code compiles, and also why it doesn't do what you expect it to do.
The question is, what do you expect it to do?
If you wanted it to output all the strings as a comma-separated set of values on each line you can do this:
Console.WriteLine(string.Join(", ", playerStuff));
If you simply wanted to concatenate all the strings and put nothing between them, replace the ", " in the above statement with "" or string.Empty:
Console.WriteLine(string.Join(string.Empty, playerStuff));
The reason you are getting the output that you are is because it is trying to write the Array object to the console; and it doesn't know how to handle it, so it is just printing out the Type of the object that it is trying to write out.
You need to do another foreach or something similar on playerStuff.
string[] playerFile = File.ReadAllLines("players.txt");
foreach (string s in playerFile)
{
//Console.WriteLine(s);
string[] playerStuff = s.Split(';');
//Inner foreach that writes out each entry of the array
foreach(var item in playerStuff)
{
Console.Write(item + " ");
}
Console.Write(Environment.NewLine);
}
Console.ReadKey();
OR even simpler
string[] playerFile = File.ReadAllLines("players.txt");
foreach (string s in playerFile)
{
Console.WriteLine(s.Replace(';', ' '));
}
Console.ReadKey();
OR a one liner
string[] playerFile = File.ReadAllLines("players.txt");
playerFile.ForEach(x => Console.WriteLine(x.Replace(';', ' ')));
Console.ReadKey();
Sample output image for all 3 of the above solutions:
Console.WriteLine docs for reference
String.Replace docs for reference
HOMEWORK QUESTION:
I need to create a simple trivia game that reads from a CSV file. My data for a particular question is structured as follows: "Question;AnswerA;AnswerB;AnswerC;AnswerD;CorrectAnswerLetter".
We're using a series of getters and setters to hold all the relevant data for a single question object, and I'm running into a problem with the array I've created to hold the four answers.
In my constructor, I'm using this code--which I believe instantiates the Answer array in question:
class TriviaQuestionUnit
{
...
const int NUM_ANSWERS = 4;
string[] m_Answers = new String[NUM_ANSWERS];
public string[] Answer
{
get { return m_Answers[]; }
set { m_Answers = value[];
}
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
}
I'm accessing the getter and setter from my TriviaQuestionBank method, which includes this code:
...
const int NUM_QUESTIONS = 15;
TriviaQuestionUnit[] m_Questions = new TriviaQuestionUnit[NUM_QUESTIONS];
...
// Answer array
public string[] GETAnswer(int index)
{
return m_Questions[index].Answer;
}
...
I'm using using StreamReader to read a line of input from my file
...
char delim = ';';
String[] inputValues = inputText.Split(delim);
...
parses the input in an array from which I create the question data. For my four answers, index 1 through 4 in the inputValues array, I populate this question's array with four answers.
...
for (int i = 0; i < NUM_ANSWERS; i++)
{
m_Questions[questionCounter].Answer[i] = inputValues[i + 1];
}
...
I'm getting errors of Syntax code, value expected on the getters/setters in my constructor, and if I change the variable to m_Answers[NUM_QUESTIONS] I get an error that I can't implicitly convert string to String[].
Hopefully I've posted enough code for someone to help point me in the right direction. I feel like I'm missing something obvious, but I just cannot make this work.
Your code has some errors that will cause compilation errors, so my first lesson for you is going to be: listen to the compiler. Some of the errors might seem a bit hard to understand sometimes, but I can ensure you that a lot of other people have had the same problems before; googling a compiler error often gives you examples from other people that are similar to your issue.
You say "In my constructor", but the problem is that your code does not have a constructor. You do however initialize fields and properties on your class and surely enough, the compiler will create a default constructor for you, but you have not defined one yourself. I am not saying that your code does not work because you do not have a constructor, but you might be using the wrong terms.
The first problem is in your first code snippet inside TriviaQuestionUnit. Your first two lines are working correctly, you are creating a constant integer with the value 4 that you use to determine how large your array is going to be and then you initialize the array with that given number.
When you do new string[NUM_ANSWERS] this will create an array, with default (empty) values.
The first problem that arises in your code is the getters and setters. The property expects you to return an array of strings which the method signature in fact is telling us:
public string[] Answer
However, looking at the getter and setter, what is it that you return?
m_Answers is a "reference" to your array, hence that whenever you write m_Answers you are referring to that array. So what happens when we add the square brackets?
Adding [] after the variable name of an array indicates that we want to retrieve a value from within the array. This is called the indexer, we supply it with an index of where we want to retrieve the value from within the array (first value starts at index 0). However, you don't supply it with a value? So what is returned?
Listen to the compiler!
Indexer has 1 parameter(s) but is invoked with (0) argument(s)
What does this tell you? It tells you that it doesn't expect the empty [] but it would expect you to supply the indexer with a number, for instance 0 like this: [0]. The problem with doing that here though, is that this would be a miss-match to the method signature.
So what is it that we want?
We simply want to return the array that we created, so just remove [] and return m_Answers directly like this:
public string[] Answer
{
get { return m_Answers; }
set { m_Answers = value; }
}
Note that you were also missing a curly bracket at the end if the set.
When fixing this, there might be more issues in your code, but trust the compiler and try to listen to it!
I'm new to programming, so please forgive my naive question .
I have double[ ] array, I manage to write it to text file using the code below:
using (System.IO.StreamWriter outfile = new System.IO.StreamWriter(#"C:\Seasonality.txt") )
{
for (int raw = 1; raw <54; raw++)
{
outfile.Write("{0} ",array[raw]);
}
}
The output text file (1 raw) consist of 54 records separated by space as demonstrated below:
1.323 2.3443 2.367 5.3453 0.3432 1.754 ........etc
What I'm trying to achieve is a function where I read a value by passing its index, i.e. index =1 for the first value in the file, or index =5 for the fifth value in the file etc..
Double GetValue (int index)
{
.....
}
P.S: please suggest if you think that changing output file structure to one value per line will ease the task.
Thanks in advance
For completeness, since you mention the option of splitting into lines per value - if you did that it would be:
var item = File.ReadLines(path).Skip(index-1).First();
(plus parsing the final value)
You're going to need to do a few things.
First: Load the file into a string. You can use File.ReadAllText() or something similar (use the IO streams if you want).
Next you need to parse your data. You have your items separated by spaces so you're going to want to use stringName.split(' '); where stringName is the variable you use for the file you just loaded and the ' ' represents the character for space (not sure how new you are but " " is a string and ' ' is a character).
Finally you want to grab the correct index, which should actually be the same as you saved the array since you're just reloading it.
Hope this helps!
Edit: Forgot that you'll need to do the double.parse thing at the end to return your value, as others have shown.
you can do as below,
double GetValue(int index)
{
return double.Parse(File.ReadLines(path).First().Split()[index-1]);
}
Note:
better you can do more validations for the results of read line, split having enough items to take by given index and use double.TryParse to convert.
double GetValue(int index)
{
return double.Parse(System.IO.File.ReadAllLines(your file)[0].Split(' ')[index]);
}
I'm working on a portion of code that is essentially trying to reduce a list of strings down to a single string recursively.
I have an internal database built up of matching string arrays of varying length (say array lengths of 2-4).
An example input string array would be:
{"The", "dog", "ran", "away"}
And for further example, my database could be made up of string arrays in this manner:
(length 2) {{"The", "dog"},{"dog", "ran"}, {"ran", "away"}}
(length 3) {{"The", "dog", "ran"}.... and so on
So, what I am attempting to do is recursively reduce my input string array down to a single token. So ideally it would parse something like this:
1) {"The", "dog", "ran", "away"}
Say that (seq1) = {"The", "dog"} and (seq2) = {"ran", "away"}
2) { (seq1), "ran", "away"}
3) { (seq1), (seq2)}
In my sequence database I know that, for instance, seq3 = {(seq1), (seq2)}
4) { (seq3) }
So, when it is down to a single token, I'm happy and the function would end.
Here is an outline of my current program logic:
public void Tokenize(Arraylist<T> string_array, int current_size)
{
// retrieve all known sequences of length [current_size] (from global list array)
loc_sequences_by_length = sequences_by_length[current_size-min_size]; // sequences of length 2 are stored in position 0 and so on
// escape cases
if (string_array.Count == 1)
{
// finished successfully
return;
}
else if (string_array.Count < current_size)
{
// checking sequences of greater length than input string, bail
return;
}
else
{
// split input string into chunks of size [current_size] and compare to local database
// of known sequences
// (splitting code works fine)
foreach (comparison)
{
if (match_found)
{
// update input string and recall function to find other matches
string_array[found_array_position] = new_sequence;
string_array.Removerange[found_array_position+1, new_sequence.Length-1];
Tokenize(string_array, current_size)
}
}
}
// ran through unsuccessfully, increment length and try again for new sequence group
current_size++;
if (current_size > MAX_SIZE)
return;
else
Tokenize(string_array, current_size);
}
I thought it was straightforward enough, but have been getting some strange results.
Generally it appears to work, but upon further review of my output data I'm seeing some issues. Mainly, it appears to work up to a certain point...and at that point my 'curr_size' counter resets to the minimum value.
So it is called with a size of 2, then 3, then 4, then resets to 2.
My assumption was that it would run up to my predetermined max size, and then bail completely.
I tried to simplify my code as much as possible, so there are probably some simple syntax errors in transcribing. If there is any other detail that may help an eagle-eyed SO user, please let me know and I'll edit.
Thanks in advance
One bug is:
string_array[found_array_position] = new_sequence;
I don't know where this is defined, and as far as I can tell if it was defined, it is never changed.
In your if statement, when if match_found ever set to true?
Also, it appears you have an extra close brace here, but you may want the last block of code to be outside of the function:
}
}
}
It would help if you cleaned up the code, to make it easier to read. Once we get past the syntactic errors it will be easier to see what is going on, I think.
Not sure what all the issues are, but the first thing I'd do is have your "catch-all" exit block right at the beginning of your method.
public void Tokenize(Arraylist<T> string_array, int current_size)
{
if (current_size > MAX_SIZE)
return;
// Guts go here
Tokenize(string_array, ++current_size);
}
A couple things:
Your tokens are not clearly separated from your input string values. This makes it more difficult to handle, and to see what's going on.
It looks like you're writing pseudo-code:
loc_sequences_by_length is not used
found_array_position is not defined
Arraylist should be ArrayList.
etc.
Overall I agree with James' statement:
It would help if you cleaned up the
code, to make it easier to read.
-Doug