How can I split different part of a sentence in a text file and put each part where I want?
I have this in a text file:
Marc;260.65
Sonia;450.37
Richard;195.00
Bob;50.00
Paul;789.00
I want to read the file using StreamReader and append the result to be something like this:
Marc, Amount: 260.65 $
Sonia, Amount : 450.37 $
...
Here's my code so far:
StreamReader File1 = new StreamReader("test.txt");
string sSentence = "";
string sAmount = "";
while (!File1.EndOfStream)
{
sSentence = File1.ReadLine();
sSentence.Split(';');
txtResult.AppendText(sSentence + ",sAmount : "+ sAmount + " $"+"\n");
}
Basically I don't know how to associate the number with the variable sAmount to append it properly.
Can you use Replace()?
sSentence.Replace(";", ", Amount: ");
Related
I got here an sample string output in numbers:
123456789
But What my goal is to make it like this:
Format: 123-45-6789
I was able to look for some codes here but they all have a fix interval , which is not fit from what I am making. It is required to make the input format to be like this "123-45-6789" but when saving it is only required 9 characters long because there is a limit to the space where it should be stored so I used this code to met the 9 characters long storation.
Input.Text = Input.Text.Trim().Replace("-", string.Empty);
Bio.SetString(UserName, "9Character", Input.Text.Trim());
But when displaying it again , it is again required to be on this format , 123-45-6789. Which is my problem.
You can also try something like:
string val = "123456789";
val = val.Substring(0, 3) + "-" + val.Substring(3, 2) + "-" + val.Substring(5) ;
Here is a working DEMO
something like,
string number = "123456789";
var output = Regex.Replace(number,
#"^(\d{3})[ -]?(\d{2})[ -]?(\d{4})( x\d+)?",
#"$1-$2-$3$4", RegexOptions.IgnorePatternWhitespace);
Console.WriteLine($"formated {output}");
output : formated 123-45-6789
Demo
I want to go through a text file and remove specific parts of the string.
In this case I want to remove the path:
PERFORMER "Charles Lloyd"
TITLE "Mirror"
FILE "Charles Lloyd\[2010] Mirror\01. I Fall In Love Too Easily.wav" WAVE
TRACK 01 AUDIO
FILE "Charles Lloyd\[2010] Mirror\02. Go Down Moses.wav" WAVE
to
PERFORMER "Charles Lloyd"
TITLE "Mirror"
FILE "01. I Fall In Love Too Easily.wav" WAVE //here are the changes
TRACK 01 AUDIO
FILE "02. Go Down Moses.wav" WAVE //here are the changes
I tried out things like: (given the string s which contains the whole text)
s = s.Remove(s.IndexOf("FILE") + 5, (s.IndexOf("\\") + 1) - s.IndexOf("FILE") - 5);
and repeat this function to remove the part between "FILE " " and the following backslash
It removes the part correctly, but I would have to manually adjust the number of times it has to run this function (run once for every backslash per line). But this algorithm lacks flexibility and I don't know how to make it approach the next line that starts with "FILE" and begin the procedure again...
If all your text is one string variable, you could first split it, and than do replacements for all strings and than join again (assume your text is variable lines):
var strings = lines.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var replacedStrings = new List<string>();
foreach (var s in strings)
{
string replaced;
if (s.StartsWith("FILE"))
{
var sWithoutFile = s.Substring(5);
replaced = s.Substring(0, 6) +
sWithoutFile.Substring(sWithoutFile.LastIndexOf("\\") + 1);
}
else
{
replaced = s;
}
replacedStrings.Add(replaced);
}
var result = string.Join(Environment.NewLine, replacedStrings);
What about Regular Expressions.
using System;
using System.Text.RegularExpressions;
class RemovePaths
{
static void Main()
{
string input = #"
PERFORMER ""Charles Lloyd""
TITLE ""Mirror""
FILE ""Charles Lloyd\[2010] Mirror\01. I Fall In Love Too Easily.wav"" WAVE
TRACK 01 AUDIO
FILE ""Charles Lloyd\[2010] Mirror\02. Go Down Moses.wav"" WAVE";
string test = #"
PERFORMER ""Charles Lloyd""
TITLE ""Mirror""
FILE ""01. I Fall In Love Too Easily.wav"" WAVE
TRACK 01 AUDIO
FILE ""02. Go Down Moses.wav"" WAVE";
Regex rgx = new Regex(#"(?<=\"").*\\(?=.+\"")");
string result = rgx.Replace(input, "");
Console.WriteLine(result == test ? "Pass" : "Fail");
}
}
Breakdown of the RegEx...
(?<=\"") <--- must start with a double-quote but be excluded using (?<=...)
.\ <--- match any text up to and including a "\". note: . matches anything
(?=.+\"") <--- skip at least one character(.+) and it must end with a double-quote(\").
Assuming that your line always start with FILE " and EndsWith " WAVE, you can use System.Io.Path.GetFilename() Function to achieve this:
If str.StartsWith("File"){
string strResult = "FILE """ + IO.Path.GetFileName(str.Substring(6,str.Length - 12)) + """ WAVE";
}
Example:
FILE "Charles Lloyd\[2010] Mirror\01. I Fall In Love Too Easily.wav" WAVE
Result:
FILE "01. I Fall In Love Too Easily.wav" WAVE
You can read more about this Function in this MSDN article
Split the array using character \ and store the last element in the array back to the string.
For Example something like this:
array = file.split('\')
file = array[array.size - 1];
So, I'm making a file transfer program from one PC in my house to the other. The client can look through the server's files and take what it wants. (Makes it very easy for moving projects/documents/music). This is an example of what a string of a file looks like:
New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"
My problem is removing : "(FILE)-(" + f.Length + " Bytes)".
How can I remove JUST that part from the string? Where the f.Length is unknown...
Thanks!
Just as an alternative to the regex answers, one option is to use LastIndexOf to find the last occurence of a known part of the string (e.g. (FILE)).
var oldString = "ThisIsAString (FILE)-(1234 Bytes";
int indexToRemoveTo = oldString.LastIndexOf("(FILE)");
// Get all the characters from the start of the string to "(FILE)"
var newString = oldString.Substring(0, indexToRemoveTo);
I hope I've got what you want
string contents = "some text (FILE)-(5435 Bytes) another text";
string result = Regex.Replace(contents, #"\(FILE\)-\(\d+ Bytes\)", "");
Console.WriteLine (result);
Prints:
some text another text
Solution to remove everything after .txt
string contents = "some text .txt (FILE)-(5435 Bytes) another text";
string lastSegment = ".txt";
var result = contents.Substring(0, contents.IndexOf(lastSegment) + lastSegment.Length);
Console.WriteLine (result);
prints some text .txt
var match = Regex.Match(pattern: #"\((.*)\)-\(\d+ Bytes\)$", input: name);
if(match.Success)
{
string fileName = match.Groups[1].Value;
}
I want to have a program that will be able to write to the file:
addr_new = serverInfo.REGION_DICT[0][serverNum]["channel"][serverChannel]["ip"]
, but must ignore the characters "" in the text
My restult: Visual studio does not ignores characters "" in string and wants strings like IP etc.. thx for help
Sry for my english
There is my Program:
string path = System.IO.Directory.GetCurrentDirectory()+ "logininfo.py";
string[] lines = {
"import serverInfo"
, "serverNum=1"
, "serverChannel=1"
, "addr_new = serverInfo.REGION_DICT[0][serverNum]["channel"][serverChannel]["ip"]"};
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.WriteLine(lines);
file.Close();
I almost forgot I want more lines, this program is trimmed
You can escape those characters with a slash:
string[] lines = {
" import serverInfo" ,
"serverNum=1" ,
"serverChannel=1" ,
"addr_new = serverInfo.REGION_DICT[0][serverNum][\"channel\"][serverChannel][\"ip\"] "};
or use a #-quoted string and use "" instead of " like so:
string[] lines = {
" import serverInfo" ,
"serverNum=1" ,
"serverChannel=1" ,
#"addr_new = serverInfo.REGION_DICT[0][serverNum][""channel""][serverChannel][""ip""] "};
You need to concatenate the strings:
"addr_new = serverInfo.REGION_DICT[0][serverNum][" + channel + "][serverChannel][" + ip + "]"};
Or if you wish for "channel" to be used as a string value, use single quotes:
"addr_new = serverInfo.REGION_DICT[0][serverNum]['channel'][serverChannel]['ip']"};
Escape the special characters
"addr_new = serverInfo.REGION_DICT[0][serverNum][\"channel\"][serverChannel][\"ip\"]"
I am new to programming. Is there a way to create multiple .txt files using
data from another file in C#.
like this:
1. we have data.txt with 100 or more strings
string1
string2
string3
...
2. we have textbox1 and textbox2 waiting for user to enter strings
3 . we need to create 100 or more files using strings from data.txt and textboxes strings: name of the fisrt file : string1+textbox1string.txt
and inside it we write:
textbox2string + string1 + textbox1string
the same pattern to create other files, second - string2+textbox1string.txt and inside second - textbox2string + string2 + textbox1string
sorry for my english i am not native speaker.
Well, it sounds like you want something like:
string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
File.WriteAllText(line + textbox1.Text + ".txt",
textbox2.Text + line + textbox1.Text);
}
Basically for very simple tasks like this, the methods in the File class allow "one shot" calls which read or write whole files at a time. For more complicated things you generally have to open a TextReader/TextWriter or a Stream.
If this wasn't what you were after, please provide more information. Likewise if you find the code hard to understand, let us know and we'll try to explain. You may fine it easier with more variables:
string[] lines = File.ReadAllLines("file1.txt");
foreach (string line in lines)
{
string newFile = line + textbox1.Text + ".txt";
string fileContent = textbox2.Text + line + textbox1.Text;
File.WriteAllText(newFile, fileContent);
}
EDIT: If you want to add a directory, you should use Path.Combine:
string newFile = Path.Combine(directory, line + textbox1.Text + ".txt");
(You can do it just with string concatenation, but Path.Combine is a better idea.)
Look into the static File class. It will have a lot of what you want.
http://msdn.microsoft.com/en-us/library/6ka1wd3w.aspx
Sure...
string textbox1string = textbox1.Text, textbox2string = textbox2.Text;
foreach(string line in File.ReadAllLines("data.txt")) {
string path = Path.ChangeExtension(line + textbox1string, "txt");
File.WriteAllText(path, textbox2string + line + textbox1string);
}