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 6 years ago.
Improve this question
Hi I'm Trying o make an atom simulation game where I can read my data from a txt file and use the data for the simulation/game. I have read the file but I am having trouble finding the commaposition from the string array. The txt file looks like this: 1,H,Hydrogen,1,1+
3,Li,Lithium,7,1+
static void Main(string[] args)
{
string commapostition;
string[] list = new string[44];
StreamReader rFile = new StreamReader(#"JUNK1.txt");
for (int i = 0; i < 44; i++)
{
list[i] = rFile.ReadLine();
}
rFile.Close();
for (int i = 0; i < 44; i++)
{
commapostition = list[i].IndexOf(',');
}
}
If each line of your file looks like what you posted:
1,H,Hydrogen,1,1+
And the order Atomic #, Symbol, Name, Mass, Charge is constant, you can do something like this:
static void Main(string[] args)
{
string filename = #"JUNK1.txt";
string[] lines = File.ReadAllLines(fileName);
for (int i = 0; i < lines.Length; i++)
{
string[] entries = lines[i].Split(',');
string atomicNumber = entries[0];
string symbol = entries[1];
string name = entries[2];
string mass = entries[3];
string charge = entries[4];
// Do stuff with these values...
}
}
Assume you have a text file JUNK1.txt with the lines:
1,H,Hydrogen,1,1+
3,Li,Lithium,7,1+
You can read this line as follows:
static void Main(string[] args)
{
// Path to the file you want to read in
var filePath = "path/to/JUNK1.txt";
// This will give you back an array of strings for each line of the file
var fileLines = File.ReadAllLines(filePath);
// Loop through each line in the file
foreach (var line in fileLines)
{
// This will give you an array of all the values that were separated by a comma
var valuesSeparatedByCommas = line.Split(',');
// Do whatever with the array valuesSeparatedByCommas
}
}
After the above code executes for the first line, the variable valuesSeparatedByCommas array will look like the following:
0 1 2 3 4
+---+---+----------+---+----+
| 1 | H | Hydrogen | 1 | 1+ |
+---+---+----------+---+-----
And now you can access each part of the line based on it's index:
// valueAtPosition0 will be '1'
var valueAtPosition0 = valuesSeparatedByCommas[0];
// valueAtPosition1 will be 'H'
var valueAtPosition1 = valuesSeparatedByCommas[1];
Related
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 last month.
Improve this question
I need to return every substring within a string array that is contained by the its integer index using for loops and if statements.
I managed to split the array and create a for loop but I am stuck when trying to compare the locations of the values using the variables.
string[] text = "The brown fox jumps";
char split = " ";
int cutFrom = '2';
int cutTo = '4';
string[] splitText = text.Split(split);
for (int i = 0; i < splitText.Length; i++)
{
if (parts[i] == parts[cutFrom])
{
return parts[i];
}
}
But this code only returns the "brown" (the 2nd array subtext), and I want to return every word from the second value until the 4th value in the array ("jumps").
Your question was a bit weirdly asked but I've tried to interpret it as best as I can.
Here is the solution for what you said:
private string[] getSubstrings(string text, char split, int cutFrom, int cutTo)
{
string[] splitText = text.Split(split);
string[] output = new string[cutTo - cutFrom];
for (int i = cutFrom; i < cutTo; i++)
{
output[i - cutFrom] = (splitText[i]);
}
return output;
}
Here is the solution with 1 based indexing which is what I think you wanted (getting the first word only is cutFrom = 1; and cutTo = 2)
private string[] getSubstrings(string text, char split, int cutFrom, int cutTo)
{
cutFrom--;
cutTo--;
string[] splitText = text.Split(split);
string[] output = new string[cutTo - cutFrom];
for (int i = cutFrom; i < cutTo; i++)
{
output[i - cutFrom] = (splitText[i]);
}
return output;
}
It is not entirely clear what your approach is here. If you want to return a list of substrings from index cutFrom to index cutTo from a larger string, then you could approach it like this:
string text = "The brown fox jumps";
string split = " ";
int cutFrom = 2;
int cutTo = 4;
string[] splitText = text.Split(split);
List<string> finalStrings = new List<string>();
for (int i = 0; i < splitText.Length; i++)
{
if (i >= cutFrom && i < cutTo)
{
finalStrings.Add(splitText[i]);
}
}
return finalStrings;
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 5 years ago.
Improve this question
I have text file (words.text) includes lines each line have characters and equivalent words like this:
A = 1
B = 2
C = 3
D = 4
I used following code to read text file
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\words.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
counter++;
}
I need to change the value of each character (number) by counter and saved it again in way to be like this
A = 3
B = 4
C = 1
D = 2
I thought about makes each word and = to be "first" and number is "second", and loop the second one
First = "A = ", Second = "1"
I have no idea how to make program to read each line and identified first and second one
You can simply split each line value by = character to get first and second value:
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\words.txt");
while((line = file.ReadLine()) != null)
{
string[] split = line.Split('=');
string First = split[0] + " = ";
string Second = split[1];
//actually you can use split[0] and split[1], the two above llines are for demo
counter++;
}
How about this...
// Getting content of the file.
string contents = File.ReadAllText(#"C:\test.txt");
// Separating content
string[] contentArr = contents.Split('\n');
List<string> characterList = new List<string>();
List<int> valueList = new List<int>();
foreach (string value in contentArr)
{
characterList.Add(string.Join("", value.ToCharArray().Where(Char.IsLetter)).Trim());
valueList.Add(Int32.Parse(string.Join("", value.ToCharArray().Where(Char.IsDigit))));
}
All the characters will be stored in the characterList as a string and all the value will be stored in the valueList as integers (int).
If you need to read or change values, you can do it like this using a forloop (or a foreach).
for (int i = 0; i < contentArr.Length; i++)
{
//valueList[i] = 5
Console.WriteLine(characterList[i] + " = " + valueList[i]);
}
//// characters
//foreach(string value in characterList)
//{
// Console.WriteLine(value);
//}
//// Values
//foreach(int value in valueList)
//{
// Console.WriteLine(value);
//}
Or, you can change value individually...
valueList[0] = 3;
valueList[1] = 4;
valueList[2] = 1;
valueList[3] = 2;
After making changes, you can write back to the file.
string output = "";
for (int i = 0; i < contentArr.Length; i++)
{
output += characterList[i] + " = " + valueList[i] + Environment.NewLine;
}
File.WriteAllText(#"C:\test.txt", output);
Online Sample 01: http://rextester.com/TIVM24779
Online Sample 02: http://rextester.com/KAUG79928
This question already has answers here:
What's the fastest way to read a text file line-by-line?
(9 answers)
Closed 5 years ago.
So I am just starting out C# with little to no knowledge, so this is more for learning for me than practical use. Therefore what I really would like to know is how I can get my code to work my way, even if there is a much simpler/quicker/smarter solution.
So what I wanna do is create a string array, and using a loop read in each line from a text file into a corresponding element of the array. That's what I tried to do here, and I would love to hear what solutions you have for this.
{
class Program
{
static void Main(string[] args)
{
StreamReader ki = new StreamReader("kiserlet.txt");
string[] a = new string[15];
Console.ReadLine();
int y = 0;
int n = 0;
for (int i = 0; i > 15; i++)
{
a[n] = Convert.ToString(ki.ReadLine());
n++;
}
for (int x = 0;x > 15;x++)
{
Console.WriteLine(a[y]);
y++;
}
Console.ReadLine();
ki.Close();
}
}
}
You can read each line of the file into an array, then iterate through it.
class Program
{
static void Main(string[] args)
{
// this will read all lines from within the File
// and automatically put them into an array
//
var linesRead = File.ReadLines("kiserlet.txt");
// iterate through each element within the array and
// print it out
//
foreach (var lineRead in linesRead)
{
Console.WriteLine(lineRead);
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a textfile and I want to read every line after a specific string in this text and store each line in a variable.
The text has this format:
[15-06-1999]
Brian
John
186
[26-08-2000]
//...
How do I read from below [15-06-1999] to the blank line and store the 3 strings in seperate variables?
I haven't found any efficient method of doing this yet.
I'm trying to do this in C#.
I can not say this is more efficient because I don't know your way( BTW: do you really have a working one?).. But at least, this works....
var date = "[15-06-1999]";
var lines = File.ReadLines(filename)
.SkipWhile(line => line != date)
.Skip(1) //skip date
.TakeWhile(line => !string.IsNullOrEmpty(line))
.ToList();
var path = "path to your text file";
string[] lines = File.ReadAllLines( path );
int lineNumber = 0;
for( int i = 0; i < lines.Length; i++ )
{
if( lines[i] == "[15-06-1999]" )
{
lineNumber = i;
break;
}
}
for( int i = lineNumber + 1; i < lines.Length; i++ )
{
// These lines are after the line with [15-06-1999] do whatever you want here
}
Make sure you import the namespace by putting this at the top: using System.IO;
Here is another method (better) which will read lines as they are requested instead of reading the whole file. Thanks to suggestion from pm100.
var path = "path to your text file";
IEnumerable<string> lines = File.ReadLines( path );
bool lineFound = false;
foreach( var thisLine in lines )
{
if( lineFound )
{
// These lines are after the line with [15-06-1999] do whatever you want here
}
else if( thisLine == "[15-06-1999]" )
{
lineFound = true;
}
}
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 6 years ago.
Improve this question
I've been trying to figure out the best approach to combining words in a string to make combinations of that string. I'm trying to do this for a class project. If the string is "The quick fox", I need to find a way to output "Thequick fox", "the quickfox", and "thequickfox". I've tried using string.split and gluing them back together, but haven't had a lot of luck. The issues is the string input could be of any size.
I decided to try this for fun. The idea here is to split the bigger problems into smaller subproblems. So I first started with strings that had 0 and 1 space. I see that with 0 space, the only possible combinations is the string items. With 1 space, I can either have that space or not.
Then I just have to recursively divide the problem until I get one of the base cases. So to that do that I Skip elements in the split array in increments of 2. That way I am guaranteed to get one of the base cases eventually. Once I do that, I run it through the program again and figure out how to add all the results of that to my current set of combinations.
Here's the code:
class Program
{
static void Main(string[] args)
{
string test1 = "fox";
string test2 = "The quick";
string test3 = "The quick fox";
string test4 = "The quick fox says";
string test5 = "The quick fox says hello";
var splittest1 = test1.Split(' ');
var splittest2 = test2.Split(' ');
var splittest3 = test3.Split(' ');
var splittest4 = test4.Split(' ');
var splittest5 = test5.Split(' ');
var ans1 = getcombinations(splittest1);
var ans2 = getcombinations(splittest2);
var ans3 = getcombinations(splittest3);
var ans4 = getcombinations(splittest4);
var ans5 = getcombinations(splittest5);
}
static List<string> getcombinations(string[] splittest)
{
var combos = new List<string>();
var numspaces = splittest.Count() - 1;
if (numspaces == 1)
{
var addcombos = AddTwoStrings(splittest[0], splittest[1]);
var withSpacesCurrent = addcombos.Item1;
var noSpacesCurrent = addcombos.Item2;
combos.Add(withSpacesCurrent);
combos.Add(noSpacesCurrent);
}
else if (numspaces == 0)
{
combos.Add(splittest[0]);
}
else
{
var addcombos = AddTwoStrings(splittest[0], splittest[1]);
var withSpacesCurrent = addcombos.Item1;
var noSpacesCurrent = addcombos.Item2;
var futureCombos = getcombinations(splittest.Skip(2).ToArray());
foreach (var futureCombo in futureCombos)
{
var addFutureCombos = AddTwoStrings(withSpacesCurrent, futureCombo);
var addFutureCombosNoSpaces = AddTwoStrings(noSpacesCurrent, futureCombo);
var combo1 = addFutureCombos.Item1;
var combo2 = addFutureCombos.Item2;
var combo3 = addFutureCombosNoSpaces.Item1;
var combo4 = addFutureCombosNoSpaces.Item2;
combos.Add(combo1);
combos.Add(combo2);
combos.Add(combo3);
combos.Add(combo4);
}
}
return combos;
}
static Tuple<string, string> AddTwoStrings(string a, string b)
{
return Tuple.Create(a + " " + b, a + b);
}
}
}
This is how I got it working, not sure if it is the best algorithm.
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a string");
string input = Console.ReadLine();
//split the input string into an array
string[] arrInput = input.Split(' ');
Console.WriteLine("The combinations are...");
//output the original string
Console.WriteLine(input);
//this loop decide letter combination
for (int i = 2; i <= arrInput.Length; i++)
{
//this loop decide how many outputs we would get for a letter combination
//for ex. we would get 2 outputs in a 3 word string if we combine 2 words
for (int j = i-1; j < arrInput.Length; j++)
{
int end = j; // end index
int start = (end - i) + 1; //start index
string output = Combine(arrInput, start, end);
Console.WriteLine(output);
}
}
Console.ReadKey();
}
//combine array into a string with space except from start to end
public static string Combine(string[] arrInput, int start, int end) {
StringBuilder builder = new StringBuilder();
bool combine = false;
for (int i = 0; i < arrInput.Length; i++) {
//first word in the array... don't worry
if (i == 0) {
builder.Append(arrInput[i]);
continue;
}
//don't append " " if combine is true
combine = (i > start && i <= end) ? true : false;
if (!combine)
{
builder.Append(" ");
}
builder.Append(arrInput[i]);
}
return builder.ToString();
}
}