Swapping each word in a string into a certain order - c#

I am trying to get a string of text from one text box and put it into the next text box inverted but readable like this. "Help please" and in the next box when I click the button it should say "please Help". I have been trying everything that I can think of. Sorry very new to this. Ill attach the code
private void button1_Click(object sender, EventArgs e)
{
string converttext = txtInputBox.Text;
StringBuilder sb = new StringBuilder(converttext.Length);
for (int i = converttext.Length - 1; i >= 0; --i)
{
sb.Append(converttext[i]);
}
string reversed = sb.ToString();
txtOutputBox.Text = reversed;
}

You can split the string on space and then reverse the result and pass it to string.Join like:
string str = "Help please";
string newStr = string.Join(" ", str.Split().Reverse());

txtOutputBox.Text = String.Join(" ", txtInputBox.Text.Split().Reverse());

Related

Trim textbox text after 20 characters used and spaces if contains spaces

I have a WinFormApp with 2 txtboxes (LongName and ShortName) with a Button.
When txt is entered in the LongName txtbox, I want to press the button to shorten all txt inside LongName txtbox to the first 20 characters imput and to remove any spaces within' the txtbox then display the results in the ShortName txtbox. I'm having a real hard time trying to get this correct. I've tried a number of ways to try but ultimately can't seem to get it right. Here is example code:
private void btnGetSN_Click(object sender, EventArgs e)
{
Regex space = new Regex(#" ");
MatchCollection spacematch = space.Matches(txtLongName.Text);
if (txtLongName.Text.Length > 20)
{
string toTrim = txtLongName.Text;
toTrim = toTrim.Trim();
txtShortName.Text = ("'" + toTrim.ToString() + "'");
}
if (spacematch.Count > 0)
{
txtLongName.Text.Replace(" ", "");
}
}//closes method
I've been able to limit the txtbox to only 20 characters in the properties but I would like to setup a If variable to allow more customization.
Am I on the right track?
No errors in the code but when executing the button, nothing happens. Any help is appreciated.
string.Replace() doesn't update the string itself, but rather returns a new string that is modified.
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
txtLongName.Text = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = txtLongName.Text.Substring(0, Math.Min(txtLongName.Text.Length, 20));
}
EDIT: Previous code will remove space from txtLongName. If that is not intended, use this instead :
private void btnGetSN_Click(object sender, EventArgs e)
{
// remove space from txtLongName
var name = txtLongName.Text.Replace(" ", string.Empty);
// take only the first 20characters from txtLongName
txtShortName.Text = name.Substring(0, Math.Min(name.Length, 20));
}
Looks like you need to write differently
private void button1_Click(object sender, EventArgs e)
{
var shortName = txtLongName.Text.Trim().Replace(" ", "");
var maxLength = (shortName.Length > 20) ? 20 : shortName.Length;
if(txtLongName.Text.Trim().Length > 0)
txtShortName.Text = shortName.Substring(0, maxLength);
}

How to find number of all occurrences of the last written Word/String in rich text box?

I have a rich text box in which i am triggering the keypress event with spacebar. The logic to find number of all occurrences of the last written word which i have implemented is:
private void textContainer_rtb_KeyPress_1(object sender, KeyPressEventArgs e)
{
//String lastWordToFind;
if (e.KeyChar == ' ')
{
int i = textContainer_rtb.Text.TrimEnd().LastIndexOf(' ');
if (i != -1)
{
String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
MessageBox.Show("Word: " + lastWordToFind + "has come: " + count + "times");
}
}
}
But its not working. Can somebody please point out the error or rectify it?
regex doesn't work lilke this:
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
this part:
this.textContainer_rtb.Text.Split(' ').ToString()
will split your text into array of strings:
string s = "sss sss sss aaa sss";
string [] arr = s.Split(' ');
arr is like this after split:
arr[0]=="sss"
arr[1]=="sss"
arr[2]=="sss"
arr[3]=="aaa"
arr[4]=="sss"
then ToString() returns type name:
System.String[]
So what you're really doing is:
int count = new Regex("ccc").Matches("System.String[]").Count;
That's why it doesn't work. You should simply do:
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text).Count;
You Regex appears to be incorrect. Try the following.
String lastWordToFind = textContainer_rtb.Text.Substring(i + 1).TrimEnd();
// Match only whole words not partial matches
// Remove if partial matches are okay
lastWordToFind = #"\b" + word + #"\b";
Console.WriteLine(Regex.Matches(richTextBox1.Text, word).Count);

How do i check if there is spaces in textBox content?

I have this code :
private void BtnScrambleText_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
BtnScrambleText.Enabled = false;
StringBuilder sb = new StringBuilder();
var words = textBox1.Text.Split(new char[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
else
{
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(words[i]);
scrmbltb.GetText();
sb.Append(scrmbltb.scrambledWord);
}
}
textBox2.AppendText(sb.ToString());
}
For example in textBox1 i did typed pressed the space bar key 7 times and then typed some words and then 5 spaces again and a word:
danny hi hello daniel hello
So lets say danny is after 7 spaces from the beginning in textBox1 and between daniel and hello there are more 5 spaces.
In my code i did:
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
But that never will happen and its not right.
I wanted to check that if before or after a word in the textBox there is any space/s add the space/s to the sb variable.
So in the end textBox2 content will be the same as in textBox1 with the same number of spaces between the words.
Now textBox2 looks like a long one string of words without any spaces between them.
My problem is how to add the same spaces between the words from textBox1 ?
I simplified your code a little, but you should find it easy to apply in your situation. The problem comes from the fact that you are losing the spaces when you do the split and they are not being added back in. The solution is to use "String.Join" when you have the finished collection of strings. In this case since you know the output size is the same as the input size, I don't see any reason to use the stringbuilder. Just use an array you size to the input.
string inputText = "This is a test";
var words = inputText.Split(new char[] { ' ' });
var outputWords = new string[words.Length];
for (int i = 0; i < words.Length; i++)
{
if (string.IsNullOrEmpty(words[i]))
{
outputWords[i] = words[i];
}
else
{
outputWords[i] = Scramble(words[i]);
}
}
string outputText = string.Join(" ",outputWords);
This statement is absolutely useless:
if (string.IsNullOrEmpty(words[i]))
{
sb.Append(words[i]);
}
It seems you need something like this (not tested):
private void BtnScrambleText_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
BtnScrambleText.Enabled = false;
StringBuilder sb = new StringBuilder();
var words = Regex.Split(textBox1.Text, #"(?=(?<=[^\s])\s+)");
foreach (string word in words)
{
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(word.Trim());
scrmbltb.GetText();
sb.Append(word.Replace(word.Trim(), scrmbltb.scrambledWord));
}
textBox2.AppendText(sb.ToString());
}
Regex.Split(textBox1.Text, #"(?=(?<=[^\s])\s+)") splits the input string with preserving spaces.
This the easy form
string text=mytextbox.Text;
while(text.Contains(" ")) //while two spaces
text=text.Replace(" "," "); //remove two spaces
If i got it right, your problem is to keep the exact number of spaces between the then scrambled words.
var words = string.Split(new char[]{' '}, StringSplitOptions.None); // this keeps the spaces as "epmty words"
var scrambled = words.Select(w => { if (String.IsNullOrEmpty(w))
return w;
else {
ScrambleTextBoxText scrmbltb = new ScrambleTextBoxText(w);
scrmbltb.GetText();
return scrmbltb.scrambledWord;
}
});
var result = string.Join(" ", scrambled);

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

I am trying to persist string from an ASP.NET textarea. I need to strip out the carriage return line feeds and then break up whatever is left into a string array of 50 character pieces.
I have this so far
var commentTxt = new string[] { };
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb != null)
commentTxt = cmtTb.Text.Length > 50
? new[] {cmtTb.Text.Substring(0, 50), cmtTb.Text.Substring(51)}
: new[] {cmtTb.Text};
It works OK, but I am not stripping out the CrLf characters. How do I do this correctly?
You could use a regex, yes, but a simple string.Replace() will probably suffice.
myString = myString.Replace("\r\n", string.Empty);
The .Trim() function will do all the work for you!
I was trying the code above, but after the "trim" function, and I noticed it's all "clean" even before it reaches the replace code!
String input: "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."
Source: http://www.dotnetperls.com/trim
This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.
var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, #"(?:\r\n|\n|\r)"));
Console.Write(newString);
// prints:
// the quick brown fox jumped over the box and landed on some rocks.
Nicer code for this:
yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);
Here is the perfect method:
Please note that Environment.NewLine works on on Microsoft platforms.
In addition to the above, you need to add \r and \n in a separate function!
Here is the code which will support whether you type on Linux, Windows, or Mac:
var stringTest = "\r Test\nThe Quick\r\n brown fox";
Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");
stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);
Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();
Try this:
private void txtEntry_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string trimText;
trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
this.txtEntry.Text = trimText;
btnEnter.PerformClick();
}
}
Assuming you want to replace the newlines with something so that something like this:
the quick brown fox\r\n
jumped over the lazy dog\r\n
doesn't end up like this:
the quick brown foxjumped over the lazy dog
I'd do something like this:
string[] SplitIntoChunks(string text, int size)
{
string[] chunk = new string[(text.Length / size) + 1];
int chunkIdx = 0;
for (int offset = 0; offset < text.Length; offset += size)
{
chunk[chunkIdx++] = text.Substring(offset, size);
}
return chunk;
}
string[] GetComments()
{
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb == null)
{
return new string[] {};
}
// I assume you don't want to run the text of the two lines together?
var text = cmtTb.Text.Replace(Environment.Newline, " ");
return SplitIntoChunks(text, 50);
}
I apologize if the syntax isn't perfect; I'm not on a machine with C# available right now.
Use:
string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));
Use double \ or use # before " for find \r or \n
htmlStr = htmlStr.Replace("\\r", string.Empty).Replace("\\n", string.Empty);
htmlStr = htmlStr.Replace(#"\r", string.Empty).Replace(#"\n", string.Empty);

asp.net flip string (swap words) between character

My scenario is i have a multiline textbox with multiple values e.g. below:
firstvalue = secondvalue
anothervalue = thisvalue
i am looking for a quick and easy scenario to flip the value e.g. below:
secondvalue = firstvalue
thisvalue = anothervalue
Can you help ?
Thanks
protected void btnSubmit_Click(object sender, EventArgs e)
{
string[] content = txtContent.Text.Split('\n');
string ret = "";
foreach (string s in content)
{
string[] parts = s.Split('=');
if (parts.Count() == 2)
{
ret = ret + string.Format("{0} = {1}\n", parts[1].Trim(), parts[0].Trim());
}
}
lblContentTransformed.Text = "<pre>" + ret + "</pre>";
}
I am guessing that your multiline text box will always have text which is in the format you mentioned - "firstvalue = secondvalue" and "anothervalue = thisvalue". And considering that the text itself doesn't contain any "=". After that it is just string manipulation.
string multiline_text = textBox1.Text;
string[] split = multiline_text.Split(new char[] { '\n' });
foreach (string a in split)
{
int equal = a.IndexOf("=");
//result1 will now hold the first value of your string
string result1 = a.Substring(0, equal);
int result2_start = equal + 1;
int result2_end = a.Length - equal -1 ;
//result1 will now hold the second value of your string
string result2 = a.Substring(result2_start, result2_end);
//Concatenate both to get the reversed string
string result = result2 + " = " + result1;
}
You could also use Regex groups for this. Add two multi line textboxes to the page and a button. For the button's onclick event add:
using System.Text.RegularExpressions;
...
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
Regex regexObj = new Regex(#"(?<left>\w+)(\W+)(?<right>\w+)");
Match matchResults = regexObj.Match(this.TextBox1.Text);
while (matchResults.Success)
{
string left = matchResults.Groups["left"].Value;
string right = matchResults.Groups["right"].Value;
sb.AppendFormat("{0} = {1}{2}", right, left, Environment.NewLine);
matchResults = matchResults.NextMatch();
}
this.TextBox2.Text = sb.ToString();
}
It gives you a nice way to deal with the left and right hand sides that you are looking to swap, as an alternative to working with substrings and string lengths.

Categories