Clipboard can copy a few words? - c#

I'm weak in English so I hope you will understand this.
I learned yesterday that Clipboard is copy.
//textBox1.Text = "My name is not exciting";
Clipboard.SetText(textBox1.Text);
textBox2.Text = Clipboard.GetText();
This code copies your everything from the textbox1 and paste it in textbox2 right?
So it's possible to copy only a few words from textbox1 and paste it in textbox2?
If you don't understand, I'm want copy only a few words not all the line.
Even if this high level code still bring me :)

Clipboard.GetText(); will return the raw copied elements.
What you can do is save them to some variable:
string text = Clipboard().GetText();
Then do something with text, to get the elements you need:
textBox2.Text = text.Substring(0, 10); // An example.
The main idea to take away from this is, GetText() will give you a string. It's up to you to slice and dice that string any way you see fit and then make use of the results.

You don't need the Clipboard for this. Your user won't like that ;)
Just create a variable like this:
string box1Content = textBox1.Text;
textBox2.Text = boxContent;
You can even skip that variable.
If you really want to use the clipboard, your way is doing that.
For just getting some text out of the textbox you can either use substring or regular expressions.
http://msdn.microsoft.com/en-us/library/aka44szs.aspx
Good luck

Daniel, the substring method is a good one to use. You simply tell it where you want to take a piece of your text and it will create a new string of just that.
textBox1.Text = "MY name is not exciting";
//pretend you only want "not exciting" to show
int index = textBox1.Text.IndexOf("not");//get the index of where "not" shows up so you can cut away starting on that word.
string partofText = textBox1.Text.Substring(index);//substring uses the index (in this case, index of "not") to take a piece of the text.
Clipboard.SetText(partofText);
textBox2.Text = Clipboard.GetText();

To my mind is better idea to take selected text from text box.
I'm not sure witch kind of text box you are using but so show example on WPF you should use TextBox.SelectedText property.

I like linq. :-)
This is a example for splitting the string, enumerable it and concats in one:
textBox1.Text = "My name is not exciting";
int firstWord = 2;
int lastWord = 4;
string[] wordList = textBox1.Text.Split(new[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
string newText = string.Concat(wordList.Where((word, count) => count >= firstWord - 1 && count < lastWord).Select(w => w + " ")).TrimEnd();
Clipboard.SetText(newText);
textBox2.Text = Clipboard.GetText();
// Result: "name is not"
Edit: and without Clipboard you can use simply this Line
textBox2.Text = newText;

Related

How to contact whole text from file into the string avoiding empty lines beetwen strings

How to get whole text from document contacted into the string. I'm trying to split text by dot: string[] words = s.Split('.'); I want take this text from text document. But if my text document contains empty lines between strings, for example:
pat said, “i’ll keep this ring.”
she displayed the silver and jade wedding ring which, in another time track,
she and joe had picked out; this
much of the alternate world she had elected to retain. he wondered what - if any - legal basis she had kept in addition. none, he hoped; wisely, however, he said nothing. better not even to ask.
result looks like this:
1. pat said ill keep this ring
2. she displayed the silver and jade wedding ring which in another time track
3. she and joe had picked out this
4. much of the alternate world she had elected to retain
5. he wondered what if any legal basis she had kept in addition
6. none he hoped wisely however he said nothing
7. better not even to ask
but desired correct output should be like this:
1. pat said ill keep this ring
2. she displayed the silver and jade wedding ring which in another time track she and joe had picked out this much of the alternate world she had elected to retain
3. he wondered what if any legal basis she had kept in addition
4. none he hoped wisely however he said nothing
5. better not even to ask
So to do this first I need to process text file content to get whole text as single string, like this:
pat said, “i’ll keep this ring.” she displayed the silver and jade wedding ring which, in another time track, she and joe had picked out; this much of the alternate world she had elected to retain. he wondered what - if any - legal basis she had kept in addition. none, he hoped; wisely, however, he said nothing. better not even to ask.
I can't to do this same way as it would be with list content for example: string concat = String.Join(" ", text.ToArray());,
I'm not sure how to contact text into string from text document
I think this is what you want:
var fileLocation = #"c:\\myfile.txt";
var stringFromFile = File.ReadAllText(fileLocation);
//replace Environment.NewLine with any new line character your file uses
var withoutNewLines = stringFromFile.Replace(Environment.NewLine, "");
//modify to remove any unwanted character
var withoutUglyCharacters = Regex.Replace(withoutNewLines, "[“’”,;-]", "");
var withoutTwoSpaces = withoutUglyCharacters.Replace(" ", " ");
var result = withoutTwoSpaces.Split('.').Where(i => i != "").Select(i => i.TrimStart()).ToList();
So first you read all text from your file, then you remove all unwanted characters and then split by . and return non empty items
Have you tried replacing double new-lines before splitting using a period?
static string[] GetSentences(string filePath) {
if (!File.Exists(filePath))
throw new FileNotFoundException($"Could not find file { filePath }!");
var lines = string.Join("", File.ReadLines(filePath).Where(line => !string.IsNullOrEmpty(line) && !string.IsNullOrWhiteSpace(line)));
var sentences = Regex.Split(lines, #"\.[\s]{1,}?");
return sentences;
}
I haven't tested this, but it should work.
Explanation:
if (!File.Exists(filePath))
throw new FileNotFoundException($"Could not find file { filePath }!");
Throws an exception if the file could not be found. It is advisory you surround the method call with a try/catch.
var lines = string.Join("", File.ReadLines(filePath).Where(line => !string.IsNullOrEmpty(line) && !string.IsNullOrWhiteSpace(line)));
Creates a string, and ignores any lines which are purely whitespace or empty.
var sentences = Regex.Split(lines, #".[\s]{1,}?");
Creates a string array, where the string is split at every period and whitespace following the period.
E.g:
The string "I came. I saw. I conquered" would become
I came
I saw
I conquered
Update:
Here's the method as a one-liner, if that's your style?
static string[] SplitSentences(string filePath) => File.Exists(filePath) ? Regex.Split(string.Join("", File.ReadLines(filePath).Where(line => !string.IsNullOrEmpty(line) && !string.IsNullOrWhiteSpace(line))), #"") : null;
I would suggest you to iterate through all characters and just check if they are in range of 'a' >= char <= 'z' or if char == ' '. If it matches the condition then add it to the newly created string else check if it is '.' character and if it is then end your line and add another one :
List<string> lines = new List<string>();
string line = string.Empty;
foreach(char c in str)
{
if((char.ToLower(c) >= 'a' && char.ToLower(c) <= 'z') || c == 0x20)
line += c;
else if(c == '.')
{
lines.Add(line.Trim());
line = string.Empty;
}
}
Working online example
Or if you prefer "one-liner"s :
IEnumerable<string> lines = new string(str.Select(c => (char)(((char.ToLower(c) >= 'a' && char.ToLower(c) <= 'z') || c == 0x20) ? c : c == '.' ? '\n' : '\0')).ToArray()).Split('\n').Select(s => s.Trim());
I may be wrong about this. I would think that you may not want to alter the string if you are splitting it. Example, there are double/single quote(s) (“) in part of the string. Removing them may not be desired which brings up the possibly of a question, reading a text file that contains single/double quotes (as your example data text shows) like below:
var stringFromFile = File.ReadAllText(fileLocation);
will not display those characters properly in a text box or the console because the default encoding using the ReadAllText method is UTF8. Example the single/double quotes will display (replacement characters) as diamonds in a text box on a form and will be displayed as a question mark (?) when displayed to the console. To keep the single/double quotes and have them display properly you can get the encoding for the OS’s current ANSI encoding by adding a parameter to the ReadAllText method like below:
string stringFromFile = File.ReadAllText(fileLocation, ASCIIEncoding.Default);
Below is code using a simple split method to .split the string on periods (.) Hope this helps.
private void button1_Click(object sender, EventArgs e) {
string fileLocation = #"C:\YourPath\YourFile.txt";
string stringFromFile = File.ReadAllText(fileLocation, ASCIIEncoding.Default);
string bigString = stringFromFile.Replace(Environment.NewLine, "");
string[] result = bigString.Split('.');
int count = 1;
foreach (string s in result) {
if (s != "") {
textBox1.Text += count + ". " + s.Trim() + Environment.NewLine;
Console.WriteLine(count + ". " + s.Trim());
count++;
}
else {
// period at the end of the string
}
}
}

How can you trimend of textbox text from another textbox text

I have two textbox's textbox1 (read/write) & textbox2 (read only), textbox1 is where you enter text at which point you press a button to pass that text into textbox2 (textbox2 continually concatenates the text from textbox1). I have a second button that I want to press to remove the text from textbox2 that is still in textbox1. Can anyone suggest how to do this?
I was thinking;
string one = textbox1.text;
string two = textbox2.text;
string newTwo = two.trimend( value of string 'one' needs to be removed );
textbox2.text = newTwo;
textbox1;
world
textbox2;
hello world
I know this sounds odd but it's a bit of a work around for an algebra calculator.
If (textbox2.Text.EndsWith(textbox1.Text))
textbox2.Text = textbox2.Text.Substring(0, textbox2.Text.Length - textbox1.Text.Length);
you can do :
var start = two.IndexOf(one);
textbox2.text = two.Substring(start);
You can also use Replace method
string newTwo = two.Replace(one,"");
As far as i undestand your question boils down to "How to implement TrimEnd?". You can use code like this:
public static class StringExtensions
{
public static string TrimEnd(this string str,
string subject,
StringComparison stringComparison)
{
var lastIndexOfSubject = str.LastIndexOf(subject, stringComparison);
return (lastIndexOfSubject == -1
|| (str.Length - lastIndexOfSubject) > subject.Length)
? str
: str.Substring(0, lastIndexOfSubject);
}
}
Then is your code-behind:
textbox2.text = textbox2.text.TrimEnd(textbox1.text, StringComparison.CurrentCulture);
#jayvee is right. Replacing with string.Empty would do.
But there's one problem with that:
When replacing "Hello" in "Hello World" the leading whitespace would remain. newTwo would be " World". You may also would want to replace multiple whitespaces via Regex as posted here and then Trim() the new string.
Also this is case sensitive.

RichTextBox SelectionStart offset with linebreaks

I'm using a RichTextBox for coloured text. Let's assume I want to use different colours for different portions of the text. This is working fine so far.
I'm currently having a problem with the SelectionStart property of the RichTextBox. I've set some text to the Text property of the RichTextBox. If the text contains \r\n\r\n the SelectionStart Position won't match the position of characters with the assigned String.
Small example (WinformsApplication. Form with a RichTextBox):
public Form1()
{
InitializeComponent();
String sentence1 = "This is the first sentence.";
String sentence2 = "This is the second sentence";
String text = sentence1 + "\r\n\r\n" + sentence2;
int start1 = text.IndexOf(sentence1);
int start2 = text.IndexOf(sentence2);
this.richTextBox1.Text = text;
String subString1 = text.Substring(start1, sentence1.Length);
String subString2 = text.Substring(start2, sentence2.Length);
bool match1 = (sentence1 == subString1); // true
bool match2 = (sentence2 == subString2); // true
this.richTextBox1.SelectionStart = start1;
this.richTextBox1.SelectionLength = sentence1.Length;
this.richTextBox1.SelectionColor = Color.Red;
this.richTextBox1.SelectionStart = start2;
this.richTextBox1.SelectionLength = sentence2.Length;
this.richTextBox1.SelectionColor = Color.Blue;
}
The RichTextBox looks like this:
As you can see, the first two characters of the second sentence are not coloured. This is the result of an offset produced by \r\n\r\n.
What is the reason for this? Should I use another control for colouring text?
How do I fix the problem in a reliable way? I've tried replacing the "\r\n\r\n"with a String.Empty, but that produces other offset problem.
Related question:
Inconsistent behaviour between in RichTextBox.Select with SubString method
It seems that the sequence \r\n counts for one character only when doing selections. You can do the measurements in a copy of the string where all \r\n are replaced by \n.
Just for completeness (I'll stick to linepogls answer for now):
I've found another way to get indices for the SelectionStart property. The RichTextBox offers a Find method, that can be used to retrieve index positions based on a specified string.
Be aware of the fact, that the text you want to highlight might not be unique and occur multiple times. You can use an overload to specify a start position for the search.

C# WinForms - Adding text to each line in a textbox

I am very new to C#. I learn best by experimentation, but of course, I will get completely stumped sometimes. I will try to explain my problem the best I can with what knowledge of the programming language I currently have.
I have been trying to create a simple tool to edit/add lines of text into a text file. I have done much researching, especially on this site, and all the information has been extremely helpful. My problem though, is adding text to both sides to a single line of text within a multi-line textbox.
So lets say I have a textbox with 2 existing lines; I want to add some text next to both sides of to one of one lines, and do the same to the next one. Here is an example of what the text would look like before and after a button is hit:
Before
is not the same as is different than
After
A is not the same as B A is different than B
The two lines in "Before" would be in textBox1 (multiline), and would be inserted to richTextBox1 as "After".
Hopefully I have explained it clearly enough, I do not know where to begin with this.
Thank you.
If you know which index you have to update the text, then you should be able to inset the value directly using insert function exposed by string class
Example:
//Get the text box value
var formatedTextboxString = this.textbox1.Text;
formatedTextboxString = formatedTextboxString.Insert(0, "A ");
formatedTextboxString = formatedTextboxString.Insert(21, "B");
//Place the formated text back to the richTextBox
this.richTextBox1.Text = formatedTextboxString;
Try
"{0} is not the same as {1} {2} is different than {3}"
In textbox1. Then use:
textbox2.Text = String.Format(textbox1.Text, A, B, A, B);
In case if you have multiline textbox:
var list = new List<string>(textBox1.Lines);
for (int i = 0; i < list.Count; ++i)
{
list[i] = "A" + list[i] + "B";
}
textBox1.Lines = list.ToArray();
string[] arr = textBox1.Text.Split(Environment.Newline);
//then loop over each line and add whatever you want :-
foreach (string s in arr)
{
//add here
}
I guess this is good enough hint to start with :)

how to find indexof substring in a text file

I have converted an asp.net c# project to framework 3.5 using VS 2008. Purpose of app is to parse a text file containing many rows of like information then inserting the data into a database.
I didn't write original app but developer used substring() to fetch individual fields because they always begin at the same position.
My question is:
What is best way to find the index of substring in text file without having to manually count the position? Does someone have preferred method they use to find position of characters in a text file?
I would say IndexOf() / IndexOfAny() together with Substring(). Alternatively, regular expressions. It the file has an XML-like structure, this.
If the files are delimited eg with commas you can use string.Split
If data is: string[] text = { "1, apple", "2, orange", "3, lemon" };
private void button1_Click(object sender, EventArgs e)
{
string[] lines = this.textBoxIn.Lines;
List<Fruit> fields = new List<Fruit>();
foreach(string s in lines)
{
char[] delim = {','};
string[] fruitData = s.Split(delim);
Fruit f = new Fruit();
int tmpid = 0;
Int32.TryParse(fruitData[0], out tmpid);
f.id = tmpid;
f.name = fruitData[1];
fields.Add(f);
}
this.textBoxOut.Clear();
string text=string.Empty;
foreach(Fruit item in fields)
{
text += item.ToString() + " \n";
}
this.textBoxOut.Text = text;
}
}
The text file I'm reading does not contain delimiters - sometimes there spaces between fields and sometimes they run together. In either case, every line is formatted the same. When I asked the question I was looking at the file in notepad.
Question was: how do you find the position in a file so that position (a number) could be specified as the startIndex of my substring function?
Answer: I've found that opening the text file in notepad++ will display the column # and line count of any position where the curser is in the file and makes this job easier.
You can use indexOf() and then use Length() as the second substring parameter
substr = str.substring(str.IndexOf("."), str.Length - str.IndexOf("."));

Categories