I have created a simple page that contains plain text like this:
Line 1
Line 2
Line 3
Line 4
And I made a c# Winform app that contains a textbox
Textbox text is like
Line 1
Line 2
I want to check if a textbox line contains any of downloaded string from my website
here's what i tried but doesn't work
int pub = 0;
int priv = 0;
WebClient data = new WebClient();
string reply = data.DownloadString("http://mytoosupd.000webhostapp.com/public-keys.html");
for (int i=0; i < textBox1.Lines.Length; i++)
{
if (textBox1.Lines[i].Contains(reply + "\n"))
{
pub++;
label5.Text = pub.ToString();
continue;
}
else if (!textBox1.Lines[i].Contains(reply))
{
priv++;
label4.Text = priv.ToString();
}
}
Split, Intersect, Any would be easy enough
string reply = data.DownloadString(..);
var result = reply
.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries)
.Intersect(textBox1.Lines)
.Any();
Debug.WriteLine($"Found = {result}");
Update
// to get a list of the intersected lines, call `ToList()` instead
var list = reply
.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries)
.Intersect(textBox1.Lines)
.ToList();
// list.Count() to get the count
// use this list where ever you like
// someTextBox.Text = String.Join(Environment.NewLine, list);
// or potentially
// someTextBox.Lines = list.ToArray();
Related
I have a software which needs to remove all of the characters before "|".
For example input
" text needs to removed | Text needs to stay "
An example output will be
"Text needs to stay"
I have the code down below. It works for single-line text but doesn't work on multiple lines. (only removes the text on the first line rest of them stays the same)
I need to make it work with multiple lines. Any ideas?
string input = richTextBox.Text;
string output = input.Substring(input.IndexOf('|') + 1);
richTextBox1.Text = output;
You could do it easily using the Lines property and a temporary List<string> to store the result of substring
List<string> newLines = new List<string>();
foreach (string s in richTextBox1.Lines)
{
// If you want only the lines with the | remove the else block
int x = s.IndexOf('|');
if(x > -1)
newLines.Add(s.Substring(x + 1).Trim());
else
newLines.Add(s);
}
richTextBox1.Lines = newLines.ToArray();
string output = "";
var myArray = input.Split("\r\n");
foreach(var ar in myArray)
if(ar.Length > 0)
output+= ar.Substring(0, ar.IndexOf('|')) + "\r\n";
Oups! i returned the first part, but i suppose you got the point
What about using LINQ for this.
E.g.:
List<string> lines = yourString.Split("\n"); //Add \r if needed
List<string> smallerLines = lines.Select(x => x.Skip(x.IndexOf('|')+1));
If needed you can always create one new string of the output:
string finalString = String.Join(String.Empty, smallerLines);
string input = richTextBox1.Text;
int len = richTextBox1.Lines.Length;
string output = "";
for (int i = 0; i <len; i++)
{
if(i!=len-1)
{
output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1) +
Environment.NewLine;
}
else
{
output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1);
}
}
richTextBox1.Text = output;
I have a string variable called: Test
The content of Test is 150 lines.
I want to count each two lines and after this two lines to inser/add a new empty line to make space between each two lines.
So in index 3 to insert empty line in index 6 to insert empty line in index 9 ,12,15.
And when i get to the last line don't add after it an empty line. Only between each two lines. Not in the beginning and not in the end only between each two lines.
This is what i have: combindedString is single string variable:
string[] ss = combindedString.Split(new string[] { "\n", "\r\n" },
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < ss.Length; i++)
ss[i] = ss[i].Trim();
combindedString = String.Join("\n", ss);
After that code which is also what i need in the end in combindedString it's content is like this:
I see many lines the first line is just text: hello world
Second line is date&time line: 6/16/2014...
Third line is another text: hello everyone
Fourth line is again date&time: 5/16/2014...
And so on all the lines are text and after it date&time.
I want after each text and date&time line to insert one empty space line.
So in the end the content in combindedString will look like:
Hello world
6/16/2014
Hi everyone
5/16/2014
This is test
5/16/2014
Instead of how it is now without the spaces. I want to add space between each two lines:
Hello world
6/16/2014
Hi everyone
5/16/2014
This is test
5/16/2014
To insert an empty/space line after each text and date&time lines.
You could do something like:
string[] lines = combindedString.Split(new string[] { "\n", "\r\n" },
StringSplitOptions.RemoveEmptyEntries);
var result = new StringBuilder();
for (int i = 0; i < lines.Length; i++)
{
if (i % 2 == 0 && i != 0) // i != 0 to not get blank line at the beginning
result.AppendLine();
result.AppendLine(lines[i].Trim());
}
combindedString = result.ToString();
See example HERE.
It is a lot easier using a List<string> instead of an array
string[] lines = new string[] {"1","2","3","4","5","6","7","8","9"};
List<string> copyList = lines.ToList();
for(int x = copyList.Count()- 1; x > 0; x--)
{
if(x % 2 == 0)
copyList.Insert(x, "");
}
string combinedString = string.Join(Environment.NewLine, copyList);
There is also the one line solution provided by Linq
string result = string.Join(Environment.NewLine,
lines.Select ((l,i) => (i % 2 == 1 ? l + Environment.NewLine : l)));
Here is a function that will add a line after every second line.
public string InsertLines(string Test)
{
var builder = new StringBuilder();
var lines = Test.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
for (var i = 0; i < lines.Length; ++i)
{
if (i != 0 && i % 2 == 0)
builder.AppendLine();
builder.AppendLine(lines[i]);
}
return builder.ToString();
}
This works:
var lookup = ss
.Concat(ss.Length % 2 == 0
? Enumerable.Empty<string>()
: new [] { "" })
.Select((x, n) => new { x, n })
.ToLookup(xn => xn.n % 2 == 0, xn => xn.x);
var query =
lookup[true]
.Zip(lookup[false], (o, e) => new [] { o, e, "" })
.SelectMany(x => x);
var result = String.Join(Environment.NewLine, query);
LINQ all the way. :-)
I'm having a bit of an issue. Lets say I have 2 text boxes, one on the left with this content:
Win
Lose
Hello
Goodbye
And one on the right, with this information:
One
Two
Three
Four
Now, on button press, I want to combine these two text boxes with colon delimitation, so it would output like this:
Win:One
Lose:Two
Hello:Three
Goodbye:Four
Any idea how I can accomplish this? Nothing I have tried thus far has worked. This is my current code, sorry. I'm not trying to have you do my work for me, I'm just rather confused:
string path = Directory.GetCurrentDirectory() + #"\Randomized_List.txt";
string s = "";
StringBuilder sb = new StringBuilder();
StreamReader sr1 = new StreamReader("Randomized_UserList.txt");
string line = sr1.ReadLine();
while ((s = line) != null)
{
var lineOutput = line+":";
Console.WriteLine(lineOutput);
sb.Append(lineOutput);
}
sr1.Close();
Console.WriteLine();
StreamWriter sw1 = File.AppendText(path);
sw1.Write(sb);
sw1.Close();
Here's a different approach that might work for you.
You can generate a couple string arrays by splitting on the new line character.
var tb1 = textBox1.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var tb2 = textBox2.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
And then use LINQ's Zip() method to combine them into a new list. The first element in each list is combined, then the second elements in each, and so on...
var combined = tb1.Zip(tb2, (s1, s2) => string.Format("{0}:{1}", s1, s2));
In order for this to work, both TextBoxes must have the same number of lines. If they differ, then Zip won't work.
The code below demonstrates one way of splitting strings and then concatenating them. I misunderstood the question at first. :)
string left = string.Format("Win{0}Lose{0}Hello{0}Goodbye", Environment.NewLine);
string right = string.Format("One{0}Two{0}Three{0}Four", Environment.NewLine);
string[] leftSplit = left.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string[] rightSplit = right.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
string output = "";
if (leftSplit.Length == rightSplit.Length)
{
for (int i = 0; i < leftSplit.Length; i++)
{
output += leftSplit[i] + ":" + rightSplit[i] + Environment.NewLine;
}
}
Well if this was a winforms app you could take advantage of the Lines property to do the following.
var tb1 = this.textBox1.Lines.Select((line, index) => new { Line = line, Index = index });
var tb2 = this.textBox2.Lines.Select((line, index) => new { Line = line, Index = index });
var q = from t1 in tb1
join t2 in tb2 on t1.Index equals t2.Index
select string.Format("{0}:{1}", t1.Line, t2.Line);
this.textBox3.Lines = q.ToArray();
textbox1.Text.Split("\n").Zip(texbox2.Text.Split("\n"),(s1,s2)=>s1+":"+s2).Aggregate("",(a,s)=>a+s+"\n")
Split method converts the string on behalf which it was call, to array of strings, by splitting it with character in parameter (new line in this case).
At this movement we have to arrays of lines from textbox1 and textbox2.
Now we use Zip method of any IEnumerable (this is an extension method as the Aggregate method is).
The outcome of Zip method is a IEnumerable that contains elements that are merge from both IEnumerables that we mentioned using function passed in the parameters, in this case it is (s1,s2)=>s1+":"+s2.
At this moment we have some IEnumerable having elements as merged lines from both textboxes. What we need to do now is to merge them into one string with Aggregate function. It a function that construct result starting with first parameter and for each element taking the result of last step and returning new value that is some kind of aggregation of the previous result and current element
You can split a string by linebreaks in the following way:
string[] lines = theString.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
I think you should split the content of both TextBoxes like that, and after that (if the resulting arrrays are of the same size), concatenate the corresponding (the first string from the first array with the first string form the second array, the second string from the first array with the second string from the second array, etc.) strings with a semicolon between them.
For example:
var lines1 = textBox1.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
var lines2 = textBox2.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string result = String.Empty;
if (lines1.Length == lines2.Length)
{
for(int i=0; i< lines1.Length; ++i)
{
result += lines1[i] + ":" + lines2[i] + Environment.NewLine;
}
}
I've tried a few different methods and none of them work correctly so I'm just looking for someone to straight out show me how to do it . I want my application to read in a file based on an OpenFileDialog.
When the file is read in I want to go through it and and run this function which uses Linq to insert the data into my DB.
objSqlCommands.sqlCommandInsertorUpdate
However I want to go through the string , counting the number of ","'s found . when the number reaches four I want to only take the characters encountered until the next "," and do this until the end of the file .. can someone show me how to do this ?
Based on the answers given here my code now looks like this
string fileText = File.ReadAllText(ofd.FileName).Replace(Environment.NewLine, ",");
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();
foreach (char c in fileText.ToArray())
{
idx++;
if (c == ',')
{
counter++;
}
if (counter == 4)
{
string x = fileText.Substring(idx);
foo.Add(fileText.Substring(idx, x.IndexOf(',')));
counter = 0;
}
}
foreach (string s in foo)
{
objSqlCommands.sqlCommandInsertorUpdate("INSERT", s);//laClient[0]);
}
However I am getting an "length cannot be less than 0" error on the foo.add function call , any ideas ?
A Somewhat hacky example. You would pass this the entire text from your file as a single string.
string str = "1,2,3,4,i am some text,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();
foreach (char c in str.ToArray())
{
idx++;
if (c == ',')
{
counter++;
}
if (counter == 4)
{
string x = str.Substring(idx);
foo.Add(str.Substring(idx, x.IndexOf(',')));
counter = 0;
}
}
foreach(string s in foo)
{
Console.WriteLine(s);
}
Console.Read();
Prints:
i am some text
9
13
17
As Raidri indicates in his answer, String.Split is definitely your friend. To catch every fifth word, you could try something like this (not tested):
string fileText = File.ReadAllText(OpenDialog.FileName).Replace(Environment.NewLine, ",");
string words[] = fileText.Split(',');
List<string> everFifthWord = new List<string>();
for (int i = 4; i <= words.Length - 1, i + 5)
{
everyFifthWord.Add(words[i]);
}
The above code reads the selected file from the OpenFileDialog, then replaces every newline with a ",". Then it splits the string on ",", and starting with the fifth word takes every fifth word in the string and adds it to the list.
File.ReadAllText reads a text file to a string and Split turns that string into an array seperated at the commas:
File.ReadAllText(OpenDialog.FileName).Split(',')[4]
If you have more than one line use:
File.ReadAllLines(OpenDialog.FileName).Select(l => l.Split(',')[4])
This gives an IEnumerable<string> where each string contains the wanted part from one line of the file
It's not clear to me if you're after every fifth piece of text between the commas or if there are multiple lines and you want only the fifth piece of text on each line. So I've done both.
Every fifth piece of text:
var text = "1,2,3,4,i am some text,6,7,8,9"
+ ",10,11,12,13,14,15,16,17,18,19,20";
var everyFifth =
text
.Split(',')
.Where((x, n) => n % 5 == 4);
Only the fifth piece of text on each line:
var lines = new []
{
"1,2,3,4,i am some text,6,7",
"8,9,10,11,12,13,14,15",
"16,17,18,19,20",
};
var fifthOnEachLine =
lines
.Select(x => x.Split(',')[4]);
How can i add a string after text if the string is not already there?
I have a textbox with the following lines:
name:username thumbnail:example.com message:hello
name:username message:hi
name:username message:hey
how can i add thumbnail:example.com after name:username to the second and third line but not the first line?
Edit: Didn't notice that you are reading from a textbox - you'll have to join the textbox lines to one string to use my example. You can do that with string.join()
Try this... this assumes that there are no spaces allowed in the username. There are probably plenty of better/more efficient ways to do this, but this should work.
var sbOut = new StringBuilder();
var combined = String.Join(Environment.NewLine, textbox1.Lines);
//split string on "name:" rather than on lines
string[] lines = combined.Split(new string[] { "name:" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in lines)
{
//add name back in as split strips it out
sbOut.Append("name:");
//find first space
var found = item.IndexOf(" ");
//add username IMPORTANT assumes no spaces in username
sbOut.Append(item.Substring(0, found + 1));
//Add thumbnail:example.com if it doesn't exist
if (!item.Substring(found + 1).StartsWith("thumbnail:example.com"))
sbOut.Append("thumbnail:example.com ");
//Add the rest of the string
sbOut.Append(item.Substring(found + 1));
}
var lines = textbox.Text.Split(new string[] { Environment.NewLine.ToString() }, StringSplitOptions.RemoveEmptyEntries);
textbox.Text = string.Empty;
for (int i = 0; i < lines.Length; i++)
{
if (!lines[i].Contains("thumbnail:example.com") && lines[i].Contains("name:"))
{
lines[i] = lines[i].Insert(lines[i].IndexOf(' '), " thumbnail:example.com");
}
}
textbox.Text = string.Join(Environment.NewLine, lines);
Hope this helps.