Combine 2 textbox contents with delimiter - c#

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

Related

Download string from website, check each line if it contains string

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

string.PadRight() doesn't seem to work in my code

I have a Powershell output to re-format, because formatting gets lost in my StandardOutput.ReadToEnd().There are several blanks to be removed in a line and I want to get the output formatted readable.
Current output in my messageBox looks like
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
What I want is
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
What am I doing wrong?
My C# knowledge still is basic level only
I found this question here, but maybe I don't understand the answer correctly. The solution doesn't work for me.
Padding a string using PadRight method
This is my current code:
string first = "";
string last = "";
int idx = line.LastIndexOf(" ");
if (idx != -1)
{
first = line.Substring(0, idx).Replace(" ","").PadRight(10, '~');
last = line.Substring(idx + 1);
}
MessageBox.Show(first + last);
String.PadLeft() first parameter defines the length of the padded string, not padding symbol count.
Firstly, you can iterate through all you string, split and save.
Secondly, you should get the longest string length.
Finally, you can format strings to needed format.
var strings = new []
{
"Microsoft.MicrosoftJigsaw All",
"Microsoft.MicrosoftMahjong All"
};
var keyValuePairs = new List<KeyValuePair<string, string>>();
foreach(var item in strings)
{
var parts = item.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries);
keyValuePairs.Add(new KeyValuePair<string, string>(parts[0], parts[1]));
}
var longestStringCharCount = keyValuePairs.Select(kv => kv.Key).Max(k => k.Length);
var minSpaceCount = 5; // min space count between parts of the string
var formattedStrings = keyValuePairs.Select(kv => string.Concat(kv.Key.PadRight(longestStringCharCount + minSpaceCount, ' '), kv.Value));
foreach(var item in formattedStrings)
{
Console.WriteLine(item);
}
Result:
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
The PadRight(10 is not enough, it is the size of the complete string.
I would probably go for something like:
string[] lines = new[]
{
"Microsoft.MicrosoftJigsaw All",
"Microsoft.MicrosoftMahjong All"
};
// iterate all (example) lines
foreach (var line in lines)
{
// split the string on spaces and remove empty ones
// (so multiple spaces are ignored)
// ofcourse, you must check if the splitted array has atleast 2 elements.
string[] splitted = line.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// reformat the string, with padding the first string to a total of 40 chars.
var formatted = splitted[0].PadRight(40, ' ') + splitted[1];
// write to anything as output.
Trace.WriteLine(formatted);
}
Will show:
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
So you need to determine the maximum length of the first string.
Assuming the length of second part of your string is 10 but you can change it. Try below piece of code:
Function:
private string PrepareStringAfterPadding(string line, int totalLength)
{
int secondPartLength = 10;
int lastIndexOfSpace = line.LastIndexOf(" ");
string firstPart = line.Substring(0, lastIndexOfSpace + 1).Trim().PadRight(totalLength - secondPartLength);
string secondPart = line.Substring(lastIndexOfSpace + 1).Trim().PadLeft(secondPartLength);
return firstPart + secondPart;
}
Calling:
string line1String = PrepareStringAfterPadding("Microsoft.MicrosoftJigsaw All", 40);
string line2String = PrepareStringAfterPadding("Microsoft.MicrosoftMahjong All", 40);
Result:
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
Note:
Code is given for demo purpose please customize the totalLength and secondPartLength and calling of the function as per your requirement.

Spliting a string multiple times by a word?

Im making the switch from Visual Basic to c#. In my project i had it split a string a few times and one of them being by a word. Here was my VB code:
Dim Item As String() = New String() {TXTItem1.Text + "-"}
If Foods.Contains(TXTItem1.Text) Then
Dim Substring As String = Foods.Split(Item, StringSplitOptions.None)(1)
Dim SPValue As String = Substring.Split(vbNewLine)(0)
MsgBox(SPValue)
Now here is my c# code:
string[] Item = new string[] {TXTSearchItem.Text + "-"};
if (Foods.Contains(TXTSearchItem.Text))
{
string Substring = Foods.Split(Item, StringSplitOptions.None)[1];
MessageBox.Show(Substring);
For some reason i cannot split it again and the MessageBox isnt even showing. Any help? Thanks!
What is the Foods object? Is that an array or a String?
If I'm not mistaken, I believe that the Split extension method on a string would create an Array of type String instead of a String.
So that MessageBox.Show method may only be showing the String array as an object or not compiling correctly since Substring is declared as a String instead of an Array.
*Edit.
Would this be what you are looking for? This would only show the information that occurs after the Item String Array in the MessageBox.Show method.
string[] Item = new string[] { TXTSearchItem.Text + "-" };
if (Foods.ToLower().Contains(TXTSearchItem.Text.ToLower()))
{
string Substring = Foods.Split(Item, StringSplitOptions.None)[1];
MessageBox.Show(Substring);
}
Rather than using string.Split, how about you just search for what you are looking for; it's probably simpler:
const string foods = "Banana-21\r\nEggs-123\r\n";
const string item = "banana";
var startIndex = foods.IndexOf(item + "-", StringComparison.CurrentCultureIgnoreCase);
var dashIndex = foods.IndexOf("-", startIndex);
var endIndex = foods.IndexOf("\r\n", startIndex);
var foodName = foods.Substring(startIndex, dashIndex - startIndex);
var footCount = foods.Substring(dashIndex + 1, endIndex - dashIndex - 1);
MessageBox.Show($"[{foodName}]: {footCount}");
But, if you really want to use string.Split, here's an example (doing something similar):
const string foods = "Banana-21\r\nEggs-123\r\nCandy-1\r\n";
var foodItems = new Dictionary<string, int>();
var records = foods.Split(new[]{ "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var foodRecord in records)
{
var parts = foodRecord.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
if (!int.TryParse(parts[1], out var foodCount))
{
foodCount = 0;
}
foodItems.Add(parts[0], foodCount);
}
After that code runs, you end up with foodItems containing:
[0] {[Banana, 21]}
[1] {[Eggs, 123]}
[2] {[Candy, 1]}
For what it's worth, it makes a lot more sense (to me, at least) to split on the line ends first, then split each line (or just the line you are interested in).

Separating string on each character and putting it in an array

I'm pulling a string from a MySQL database containing all ID's from friends in this format:
5+6+12+33+1+9+
Now, whenever i have to add a friend it's simple, I just take the the string and add whatever ID and a "+". My problem lies with separating all the ID's and putting it in an array. I'm currently using this method
string InputString = "5+6+12+33+1+9+";
string CurrentID = string.Empty;
List<string> AllIDs = new List<string>();
for (int i = 0; i < InputString.Length; i++)
{
if (InputString.Substring(i,1) != "+")
{
CurrentID += InputString.Substring(i, 1);
}
else
{
AllIDs.Add(CurrentID);
CurrentID = string.Empty;
}
}
string[] SeparatedIDs = AllIDs.ToArray();
Even though this does work it just seems overly complicated for what i'm trying to do.
Is there an easier way to split strings or cleaner ?
Try this:-
var result = InputString.Split(new char[] { '+' });
You can use other overloads of Split
as well if you want to remove empty spaces.
You should to use the Split method with StringSplitOptions.RemoveEmptyEntries. RemoveEmptyEntries helps you to avoid empty string as the last array element.
Example:
char[] delimeters = new[] { '+' };
string InputString = "5+6+12+33+1+9+";
string[] SeparatedIDs = InputString.Split(delimeters,
StringSplitOptions.RemoveEmptyEntries);
foreach (string SeparatedID in SeparatedIDs)
Console.WriteLine(SeparatedID);
string[] IDs = InputString.Split('+'); will split your InputString into an array of strings using the + character
var result = InputString.Split('+', StringSplitOptions.RemoveEmptyEntries);
extra options needed since there is a trailing +

Alternatively upper- and lowercase words in a string

I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"

Categories

Resources