I am currently making myself a little tool.
Essentially I have this list which goes like this:
NPWR00160_00 LittleBigPlanet
NPWR00163_00 Warhawk
NPWR00179_00 Pure
NPWR00180_00 Midnight Club: Los Angeles
NPWR00181_00 echochromeâ„¢
NPWR00187_00 WipEout® HD
This is currently typed into a richTextBox.
I am trying to do this, get the NPWRXXXXXX of the line and save it as a string, and then the Games Name and save that as another string for which I can go ahead and do what I was originially going to do with it. But for each line of the richTextBox which carries on with that formation as above.
Not too sure how to get a line from the richTextBox and save it as a string, in which I can repeat that process for every single line of the richTextBox.
For what I have tried, I gave myself an example that the string was NPWR02727_00 Skydive: Proximity Flight. What I did was this:
string game = "NPWR02727_00 Skydive: Proximity Flight";
string NPWR = game.Substring(0,13);
string gamename = game.Remove(0, 13);
richTextBox2.AppendText("NPWRID: " + NPWR + " Game: " + gamename + Environment.NewLine);
Which actually does successfully save the strings and write it in the second text box as the new form.
Only issue is I'm not sure how to convert a line from the RichTextBox and turn it into a string, and repeat the process for each line in the rich text box
EDIT
So I found out how to turn a string into a line from the richTextBox..
string line = richTextBox1.Lines[0];
So this will get the first line and save it as the string "line"
This now updates the code to
string game = richTextBox1.Lines[0];
string NPWR = game.Substring(0,13);
string gamename = game.Remove(0, 13);
richTextBox2.AppendText("NPWRID: " + NPWR + " Game: " + gamename + Environment.NewLine);
Now how do I get this code to run for every line, I understand I need something to repeat it, and something to change the 0 to count up by 1 everytime it repeats?
EDIT AGAIN
Awesome, forget the above edit, thanks a lot!
I suggest you do something similar to this:
var codes = new List<string>();
var games = new List<string>();
foreach(var s in richTextBox1.Lines)
{
string[] p = s.Split(new char[] { ' ' }, 2);
if (p.Count() == 1) { continue; }
codes.Add(p[0]);
games.Add(p[1]);
}
Basically, we are declaring two Lists of the type string, to store respectively the code and the name of the game. Then we proceed in looping through the Lines property of the RichTextBox, and for each line, we split the line by the first index(space) we find; asking for a maximum of two strings, to avoid splitting any forthcoming elements; in case the name of the game contains spaces.
For the two substrings obtained, we proceed by saving the first part into the List codes, and the second one into the List games.
For further uses(traversing codes/names) we could access the two Lists
for(int c = 0; c < codes.Count; c++)
{
MessageBox.Show(codes[c] + string.Empty + games[c]);
}
Related
Super new to C# apologize upfront. My goal is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Numbers can be from 1 to 9. So 1 will be the first word (not 0).
My plan of attack is to split the string, having one variable of int data-type (int lookingForNum) and the other variable turning that into a String data-type(string stringLookingForNum), then for each loop over the array looking to see if any elements contain string stringLookingForNum, if they do I add it to an emptry string variable, lastly add 1 to int variable lookingForNum. My issue seems to be with the if statement with the Contains method. It will not trigger the way I currently have it written. Hard coding in if (word.Contains("1")) will trigger that code block but running it as written below will not trigger the if statement.Please can anyone tell my WHY!?!? I console.log stringLookingForNum and it is for sure a string data type "1"
This noobie would appreciate any help. Thanks!
string testA = "is2 Thi1s T4est 3a"; //--> "Thi1s is2 3a T4est"
string[] arrayTestA = testA.Split(' ');
string finalString = string.Empty;
int lookingForNum = 1; //Int32
foreach (string word in arrayTestA){
string stringLookingForNum = lookingForNum.ToString();
//Don't understand why Contains is not working as expected here)
if (word.Contains(stringLookingForNum)){
finalString = finalString + $"{word} ";
}
lookingForNum++;
}
you need this - look for the string with 1, the look for the string with 2 etc. Thats not what you are doing
you look at the first string and see if it contains one
then look at the second one and see if it contains 2
....
int lookingForNum = 1;
while(true){ // till the end
string stringLookingForNum = lookingForNum.ToString();
bool found = false;
foreach (string word in arrayTestA){
if (word.Contains(stringLookingForNum)){
finalString = finalString + $"{word} ";
found = true;
break;
}
}
if(!found) break;
lookingForNum++;
}
To sort you should simply use OrderBy, and since you need to sort by number inside a word - just Find and extract a number from a string
string testA = "is2 Thi1s T4est 3a";
var result = testA.Split().OrderBy(word =>
Int32.Parse(Regex.Match(word, #"\d+").Value));
Console.WriteLine(string.Join(" ", result));
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];
I have a list of strings stored in an ArrayList. I want to split them by every occurrence of ';'. The problem is, whenever I try to display them using MessageBox, there's an excess space or unnecessary value that gets displayed.
Sample input (variable = a):
Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;
Below is a line of code I used to split them:
string[] display_document = (a[0] + "").Split(';');
Code to display:
foreach (object doc_properties in display_document)
{
TextBox aa = new TextBox();
aa.Font = new Font(aa.Font.FontFamily, 9);
aa.Text = doc_properties.ToString();
aa.Location = new Point(pointX, pointY);
aa.Size = new System.Drawing.Size(80, 25);
aa.ReadOnly = true;
doc_panel.Controls.Add(aa);
doc_panel.Show();
pointY += 30;
}
The output that displays are the following:
How do I remove the last occurrence of that semicolon? I really need help fixing this. Thank you so much for all of your help.
Wouldnt It be easiest to check if the input ends with a ";" before splitting it, and if so remove the last character? Sample code:
string a = "Arial;16 pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
if (a.EndsWith(";"))
{
a = a.Remove(a.LastIndexOf(";"));
}
//Proceed with split
Split will not print last semicolon if no space character is added and your input is a string.
I don't know why you prefer an array list (which probably is the reason of this strange behaviour) but if you could use your input as a string you could try that
string a = "Arial;16pt;None;None;None;None;None;None;FF0000;None;100;Normal;None;Normal;";
string[] display_document = a.Split(';');
foreach (object doc_properties in display_document)
{
//The rest of your code
}
I've assigned some string values from a data set to the string b.
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
string b = ds.Tables[0].Rows[i].ItemArray[0] + " " + ds.Tables[0].Rows[i].ItemArray[1];
}
What I want to do is add those values, and finally show as a sentence.
Example: if "dog", "cat", and "cow" are the values read by the for loop, I want to display "dog cat cow" in a message box. How to do that?
Edit: Since it appears you are interested in the String.Join() method this could work perfectly for you. You have plenty of options here but if you want to go that route here's how.
First create an array of the items you are returning then you can simple use the String.Join() method to concatenate the items in the array like so:
string separator = whatever seperator you want "," or "|"
string d = String.Join(separator, animalArray);
MessageBox.Show(d);
The first thing you'll need to do is make sure you have imported the System.Windows.Forms namespace to enable your ability to call the MessageBox function.
Essentially you are already there with the concatenation of the strings. If you are looking for a cleaner option I would recommend using String.Format() or using the newer method of concatenation by applying a '$' character in front of a string which allows you to simple add your variables between curly braces.
For example: $"Hello my name is {name}."
What's wrong with the above?
You already have them in your string variable b.
Enclose it in MessageBox.Show(); instead of adding the variable.
string b = "";
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
b += ds.Tables[0].Rows[i].ItemArray[0] + " " + ds.Tables[0].Rows[i].ItemArray[1] + "\n";
}
MessageBox.Show(b);
My Goal: I want to parse a file and display it in a textbox. Here's the code (thanks to Aviral Singh).
private void Form1_Load(object sender, EventArgs e)
{
var path = #"C:\Users\Smith\Desktop\Settings.txt"; //Path to settings file.
RichTextBox rtb = new RichTextBox();
System.IO.StreamReader sis = new System.IO.StreamReader(path);
rtb.Text = sis.ReadToEnd();
sis.Close();
foreach (string line in rtb.Lines)
{
if (line.Contains("Installation Technical Manual:") == true)
{
string numbers = line.Substring(line.IndexOf("Installation Technical Manual:"));
textBox1.Text = numbers;
}
}
}
Text file looks like this:
My Problem: The textbox in my program displays entire line: Installation Technical Manual: (1234567890).
I just want the number with brackets (1234567890). to be displayed in the textbox. What changes should I make to the code to remove the words and just display numbers with brackets around it? Thanks for your help. :)
numbers = "(" + new String(numbers.Where(Char.IsDigit).ToArray()) + ")";
The problem is that IndexOf() is going to give you the starting position of the string which you're asking for the index of. Which in your example is going to be 0, so a Substring call that starts at 0 is going to return you the entire string.
What you really want to do is Substring(IndexOf("Installation Technical Manual:") + "Installation Technical Manual:".Length). That will give you whatever comes after your string.
Assuming you have ':' in your line always,
if(line.Contains(":"))
{
string numbers = line.Split(':')[1];
textBox1.Text = numbers;
}
The reason your code is not working as you have used the substring method as with one parameter, so it is used as :
public string Substring(
int startIndex
)
See: http://msdn.microsoft.com/en-us/library/hxthx5h6.aspx
And you are passing in, line.IndexOf("Installation Technical Manual:")
which will return ).
See here: http://msdn.microsoft.com/en-us/library/k8b1470s.aspx
So you are essentially saying return Substring of string Installation Technical Manual:(number) starting at 0 which basically returns the whole line.