Read each word in text file separately [closed] - c#

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

Related

Return strings within start and finish integer values? [closed]

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;

List<string> summation [closed]

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 7 months ago.
Improve this question
I have a list of string with comma separated in each of them.
For eg:
abc,1,2,0,0,0,3,1,0
def,2,0,1,0,0,1,0,0
I would like to generate a summation of that two strings starting from index 1 of each string.
Output eg:
Output,3,2,1,0,0,4,1,
Below is my current code. But I am looking for shorter version of it.
List<string> panelBinCodeStringList = new List<string>;
//panelBinCodeStringList has more than 2 strings.
List<int> totalTmpString = new List<int>();
foreach (var binCodeString in panelBinCodeStringList)
{
var tmp = binCodeString.Substring(binCodeString.IndexOf(',') + 1).Split(',').ToList();
for (int i =0; i < tmp.Count; i++)
{
if (totalTmpString.Count() <= i)
{
totalTmpString.Add(Convert.ToInt16(tmp[i]));
}
else
{
totalTmpString[i] += Convert.ToInt16(tmp[i]);
}
}
}
totalFailedBinCodes = "Output," + string.Join(",", totalTmpString);
Not very efficient, but working.
var abcTxt = "abc,1,2,0,0,0,3,1,0";
var defTxt = "def,2,0,1,0,0,1,0,0";
var abcList = abcTxt.Split(",").Skip(1).Select(int.Parse).ToList();
var defList = defTxt.Split(",").Skip(1).Select(int.Parse).ToList();
if (abcList.Count != defList.Count)
throw new Exception("Collections do not have the same size");
var output = "Output";
for (var i = 0; i < abcList.Count; i++) output += "," + (abcList[i] + defList[i]);
Result:
string[] a = abc.Split(",");
string[] d = def.Split(",");
String output = "Output";
for(int i= 1; i < a.Length; i++)
{
output+= "," + (int.Parse(a[i]) + int.Parse(d[i]));
}
Approach with Linq.Zip()
string s1 = "abc,1,2,0,0,0,3,1,0";
string s2 = "def,2,0,1,0,0,1,0,0";
Func<string, IEnumerable<int>> ToInt = x => x.Split(',').Skip(1).Select(int.Parse);
string res = "output," + string.Join(",", ToInt(s1).Zip(ToInt(s2),(x, y) => x+y));

How to read a comma position from an Array C# [closed]

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

How to remove spaces to make a combination of strings [closed]

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

C# .txt file: Reading a substring in next line if previous line contains "X"

I am looking to read from a text file and if a line contains "XYZ" I need to return substrings within that line, then have the next line read for another substring.
There will be several lines that will return the "XYZ" and on each of these I will require the substring from the following line (Each of these will be a different value).
Currently I can return all instances of the substrings in the lines with "XYZ" but then either keep returning the same substring (which should be unique each time) from the line below the first "XYZ" or just, as below, each character individually.
So in the below snippet, from the log. If a line contains XYZ then I need to move to the next line and pull the Date/Time/and Batch Name Number.
XYZ will repeat several times through out the log, with different results each time.
2015-07-02 11:03:13,838 [1] INFO Place (null) (null) (null) – btnAction_Click, Completed Scan for _HAH_Claim_T, XYZ
2015-07-02 11:03:14,432 [1] INFO Place (null) (null) (null) – btnAction_Click, Set batch name 1234567
string[] lines = File.ReadAllLines(#"Text Document.txt");
foreach (string line in lines)
{
int success = line.IndexOf("XYZ");
if (success > 0)
{
string pass = "Pass";
string date = line.Substring(0, 10);
string time = line.Substring(11, 12);
int ID = line.LastIndexOf("XYZ");
if (ID != 0)
{
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
}
string currentLine;
string batchID;
for (int i = 0; i < lines.Length; i++)
{
currentLine = lines.Skip(6).First();
batchID = currentLine.Substring(100);
Console.WriteLine("\tBatchID{0}", batchID[i]);
}
Console.WriteLine();
}
}
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
I do not completely understand the question as it is a bit abstract as to what you want to extract from each line but something like this will hopefully get you on the right track
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.Contains("XYZ") && !reader.EndOfStream)
{
var nextLine = reader.ReadLine();
var pass = "Pass";
var date = nextLine.Substring(0, 10);
var time = nextLine.Substring(11, 12);
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
}
}
}
the line variable is the one containing XYZ and next line is the line subsequent to that. If this is not meeting you requirements the please update the question to be a bit more specific
I would say something like this?
string[] lines = File.ReadAllLines(#"Text Document.txt");
for(int i = 0; i < lines.Length(); i++){
if(lines[i].Contains("XYZ")){
string pass = "Pass";
string date = line.Substring(0, 10);
string time = line.Substring(11, 12);
Console.WriteLine("\n\t" + pass + " Date: {0}\tTime: {1}", date, time);
// Retrieve the value in the next line
string nextLineAfterXYZ = lines[i + 1];
batchID = nextLineAfterXYZ.Substring(100);
Console.WriteLine("\tBatchID{0}", batchID);
}
}
You should add some error-handling, in case it's the last line (IndexOutOfBound) etc.
string[] lines = File.ReadAllLines(#"E:Sum.txt");
string str = string.Empty;
foreach (string line in lines)
{
if (line.Contains("x"))
{
str += line;
Console.WriteLine();
continue;
}
break;
}
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();

Categories