I have the textbox that takes some string. This string could be very long. I want to limit displayed text (for example to 10 characters) and attach 3 dots like:
if text box takes value "To be, or not to be, that is the question:" it display only "To be, or..."
Or
if text box takes value "To be" it display "To be"
Html.DevExpress().TextBox(
tbsettings =>
{
tbsettings.Name = "tbNameEdit";;
tbsettings.Width = 400;
tbsettings.Properties.DisplayFormatString=???
}).Bind(DataBinder.Eval(product, "ReportName")).GetHtml();
You should use a Label control to display the data. Set AutoSize to false and AutoEllipsis to true. There are good reasons why a TextBox does not have this functionality, among which:
where are you going to store the truncated data?
if the user selects the text to edit or even copy, how do you handle that?
If you counter-argument is that the TextBox is read-only, then that is only more reason to re-think the control you are using for this.
If you need to use a regex, you can do this:
Regex.Replace(input, "(?<=^.{10}).*", "...");
This replaces any text after the tenth character with three dots.
The (?<=expr) is a lookbehind. It means that expr must be matched (but not consumed) in order for the rest of the match to be successful. If there are fewer than ten characters in the input, no replacement is performed.
Here is a demo on ideone.
Try this:
string displayValue = !string.IsNullOrWhiteSpace(textBox.Text) && textBox.Text.Length > 10
? textBox.Text.Left(10) + "..."
: textBox.Text;
In an extension method:
public static string Ellipsis(this string str, int TotalWidth, string Ellipsis = "...")
{
string output = "";
if (!string.IsNullOrWhiteSpace(str) && str.Length > TotalWidth)
{
output = output.Left(TotalWidth) + Ellipsis;
}
return output;
}
Using it would be:
string displayValue = textBox.Text.Ellipsis(10);
string textToDisplay = (inputText.Length <= 10)
? inputText
: inputText.Substring(0, 10) + "...";
Something like this?
static void SetTextWithLimit(this TextBox textBox, string text, int limit)
{
if (text.Length > limit)
{
text = text.SubString(0, limit) + "...";
}
textBox.Text = text;
}
Show what you have tried and where you are stuck.
You don't need to use regex
string s = "To be, or not to be, that is the question:";
s = s.Length > 10 ? s.Remove(10, s.Length - 10) + "..." : s;
string maxStringLength = 10;
string displayStr = "A very very long string that you want to shorten";
if (displayStr.Length >= maxStringLength) {
displayStr = displayStr.Substring(0, maxStringLength) + " ...";
}
//displayStr = "A very very long str ..."
Related
I have a big String in my program.
For Example:
String Newspaper = "...Blablabla... What do you like?...Blablabla... ";
Now I want to cut out the "What do you like?" an write it to a new String. But the problem is that the "Blablabla" is everytime something diffrent. Whit "cut out" I mean that you submit a start and a end word and all the things wrote between these lines should be in the new string. Because the sentence "What do you like?" changes sometimes except the start word "What" and the end word "like?"
Thanks for every responds
You can write the following method:
public static string CutOut(string s, string start, string end)
{
int startIndex = s.IndexOf(start);
if (startIndex == -1) {
return null;
}
int endIndex = s.IndexOf(end, startIndex);
if (endIndex == -1) {
return null;
}
return s.Substring(startIndex, endIndex - startIndex + end.Length);
}
It returns null if either the start or end pattern is not found. Only end patterns that follow the start pattern are searched for.
If you are working with C# 8+ and .NET Core 3.0+, you can also replace the last line with
return s[startIndex..(endIndex + end.Length)];
Test:
string input = "...Blablabla... What do you like?...Blablabla... ";
Console.WriteLine(CutOut(input, "What ", " like?"));
prints:
What do you like?
If you are happy with Regex, you can also write:
public static string CutOutRegex(string s, string start, string end)
{
Match match = Regex.Match(s, $#"\b{Regex.Escape(start)}.*{Regex.Escape(end)}");
if (match.Success) {
return match.Value;
}
return null;
}
The \b ensures that the start pattern is only found at the beginning of a word. You can drop it if you want. Also, if the end pattern occurs more than once, the result will include all of them unlike the first example with IndexOf which will only include the first one.
You have to do a substring, like the example below. See source for more information on substrings.
// A long string
string bio = "Mahesh Chand is a founder of C# Corner. Mahesh is also an
author, speaker, and software architect. Mahesh founded C# Corner in
2000.";
// Get first 12 characters substring from a string
string authorName = bio.Substring(0, 12);
Console.WriteLine(authorName);
In this case I would do it like this, cut the first part and then the second and concatenate with the fixed words using them as a parameter for cutting.
public string CutPhrase(string phrase)
{
var fst = "What";
var snd = "like?";
string[] cut1 = phrase.Split(new[] { fst }, StringSplitOptions.None);
string[] cut2 = cut1[1].Split(new[] { snd }, StringSplitOptions.None);
var rst = $"{fst} {cut2[0]} {snd}";
return rst;
}
I got a little "problem". I have these two strings (one showing the message, and the other showing the index where "##Documents##" start):
string text = currentNode.Properties["menuEntry"].Value;
string index = text.IndexOf("##Documents##").ToString();
I want to have another string for the message WITHOUT "##Documents##". Any solution to continue from the code up above, or any other solution?
For example: Message: blablabla ##Documents## 123
And what I want to show: blablabla 123
Thanks and sorry for the noobish question.
Just use the Replace() method like this:
string text = currentNode.Properties["menuEntry"].Value;
string message= text.Replace("##Documents##",string.Empty);
Just concatenate the substrings that occur before and after that substring if it is found.
int index = text.IndexOf("##Documents##");
string newText = text;
if(index > -1)
newText = text.SubString(0, index) + text.SubString(index +13);
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.
I use WinForms c#.I have string value like below,
string Something = "1,5,12,34,";
I need to remove last comma in a string. So How can i delete it ?
Try string.TrimEnd():
Something = Something.TrimEnd(',');
King King's answer is of course correct, and Tim Schmelter's comment is also good suggestion in your case.
But if you really want to remove the last comma in a string, you should find the index of the last comma and remove it like this:
string s = "1,5,12,34,12345";
int index = s.LastIndexOf(',');
Console.WriteLine(s.Remove(index, 1));
Output will be:
1,5,12,3412345
Here is a demonstration.
It is unlikely that you want this way but I want to point it out. And remember, the String.Remove method doesn't remove any characters in the original string, it returns new string.
Try string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);
The TrimEnd method takes an input character array and not a string.
The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.
static string TrimTrailingChars(string value)
{
int removeLength = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
char let = value[i];
if (let == '?' || let == '!' || let == '.')
{
removeLength++;
}
else
{
break;
}
}
if (removeLength > 0)
{
return value.Substring(0, value.Length - removeLength);
}
return value;
}
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123
Try below
Something..TrimEnd(",".ToCharArray());
Or you can convert it into Char Array first by:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it
When you have spaces at the end. you can use beliow.
ProcessStr = ProcessStr.Replace(" ", "");
Emails = ProcessStr.TrimEnd(';');
Try this,
string Something1= Something.Substring(0, Something.Length - 1 );
How can I get "MyLibrary.Resources.Images.Properties" and "Condo.gif" from a "MyLibrary.Resources.Images.Properties.Condo.gif" string.
I also need it to be able to handle something like "MyLibrary.Resources.Images.Properties.legend.House.gif" and return "House.gif" and "MyLibrary.Resources.Images.Properties.legend".
IndexOf LastIndexOf wouldn't work because I need the second to last '.' character.
Thanks in advance!
UPDATE
Thanks for the answers so far but I really need it to be able to handle different namespaces. So really what I'm asking is how to I split on the second to last character in a string?
You can use LINQ to do something like this:
string target = "MyLibrary.Resources.Images.Properties.legend.House.gif";
var elements = target.Split('.');
const int NumberOfFileNameElements = 2;
string fileName = string.Join(
".",
elements.Skip(elements.Length - NumberOfFileNameElements));
string path = string.Join(
".",
elements.Take(elements.Length - NumberOfFileNameElements));
This assumes that the file name part only contains a single . character, so to get it you skip the number of remaining elements.
You can either use a Regex or String.Split with '.' as the separator and return the second-to-last + '.' + last pieces.
You can look for IndexOf("MyLibrary.Resources.Images.Properties."), add that to MyLibrary.Resources.Images.Properties.".Length and then .Substring(..) from that position
If you know exactly what you're looking for, and it's trailing, you could use string.endswith. Something like
if("MyLibrary.Resources.Images.Properties.Condo.gif".EndsWith("Condo.gif"))
If that's not the case check out regular expressions. Then you could do something like
if(Regex.IsMatch("Condo.gif"))
Or a more generic way: split the string on '.' then grab the last two items in the array.
string input = "MyLibrary.Resources.Images.Properties.legend.House.gif";
//if string isn't already validated, make sure there are at least two
//periods here or you'll error out later on.
int index = input.LastIndexOf('.', input.LastIndexOf('.') - 1);
string first = input.Substring(0, index);
string second = input.Substring(index + 1);
Try splitting the string into an array, by separating it by each '.' character.
You will then have something like:
{"MyLibrary", "Resources", "Images", "Properties", "legend", "House", "gif"}
You can then take the last two elements.
Just break down and do it in a char loop:
int NthLastIndexOf(string str, char ch, int n)
{
if (n <= 0) throw new ArgumentException();
for (int idx = str.Length - 1; idx >= 0; --idx)
if (str[idx] == ch && --n == 0)
return idx;
return -1;
}
This is less expensive than trying to coax it using string splitting methods and isn't a whole lot of code.
string s = "1.2.3.4.5";
int idx = NthLastIndexOf(s, '.', 3);
string a = s.Substring(0, idx); // "1.2"
string b = s.Substring(idx + 1); // "3.4.5"