In my ASP.NET page, I have a string (returned from SQL db). I would like to bold certain part of the string text based on given text position.
For example, if I have a string as follows:
"This is an example to show where to bold the text"
And I am given character start position: 6 and end position: 7, then I would bold the word "is" in my string, getting:
"This is an example to show where to bold the text"
Any ideas?
EDIT: Keep in mind I need to use the start/end position as there may be duplicate words in the string.
Insert a close tag into position 7 of the string
Insert an open tag into position 5 (6 - 1) of the string.
You will get a string like "This is an example…"
I.e. modify string (insert markup) from end to start:
var result = str.Insert(7, "</b>").Insert(6 - 1, "<b>");
You can use String.Replace method for this.
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
string s = "This is an example to show where to bold the text".Replace(" is ", " <b>is</b> ");
Console.WriteLine(s);
Here is a DEMO.
Since you clear what you want, you can use StringBuilder class.
string s = "This is an example to show where to bold the text";
var sb = new StringBuilder(s);
sb.Remove(5, 2);
sb.Insert(5, "<b>is</b>");
Console.WriteLine(s);
Here is a DEMO.
NOTE: Since you didn't see <b> tags as an output, it doesn't mean they are not there ;)
You need to do something like this...
**
strStart = MID(str, 0 , 7) ' Where 7 is the START position
str2Replace = "<b>" & MID(str, 8, 10) & "</b>" ' GRAB the part of string you want to replace
str_remain = MId(str, 11, Len(str)) ' Remaining string
Response.write(strStart & str2Replace & str_remain )
**
First find the string to replace in your full string.
Replace the string with <b>+replacestring+</b>
string str="This is an example to show where to bold the text";
string replaceString="string to replace"
str=str.Replace(replaceString,<b>+replaceString+</b>);
Edit 1
string replaceString=str.Substring(6,2);
str=str.Replace(replaceString,<b>+replaceString+</b>);
SubString Example:
http://www.dotnetperls.com/substring
Edit 2
int startPosition=6;
int lastPosition=7;
int lastIndex=lastPosition-startPosition+1;
string str="This is an example to show where to bold the text";
string replaceString=str.Substring(startPosition,lastIndex);
str=str.Replace(replaceString,<b>+replaceString+</b>);
Related
I've been working on a tool to modify a text file to change graphics settings for a game. A few examples of the settings are as follows:
sg.ShadowQuality=0
ResolutionSizeX=1440
ResolutionSizeY=1080
bUseVSync=False
I want to be able to find sg.ShadowQuality=(rest of line, regardless of what is after this text), and replace it. This is so that a user can set this to say, 10 then 1 without having to check for 10 and 1 etc.
Basically, I'm try to find out what I need to use to find/replace a string in a text file without knowing the end of the string.
My current code looks like:
FileInfo GameUserSettings = new FileInfo(#SD + GUSDirectory);
GameUserSettings.IsReadOnly = false;
string text = File.ReadAllText(SD + GUSDirectory);
text = text.Replace("sg.ShadowQuality=0", "sg.ShadowQuality=" + Shadows.Value.ToString());
File.WriteAllText(SD + GUSDirectory, text);
text = text.Replace("sg.ShadowQuality=1", "sg.ShadowQuality=" + Shadows.Value.ToString());
File.WriteAllText(SD + GUSDirectory, text);
SD + GUSDirectory is the location of the text file.
The file must have readonly Off to be edited, otherwise the game can revert the settings back, hence the need for this.(It is turned back to readonly On after any change, its just not included in this code provided)
You can do it like you do, if you use a regular expression to match all the line
FileInfo gameUserSettings = new FileInfo(Path.Combine(#SD, GUSDirectory)); //name local varaible in camelCase, use Path.Combine to combine paths
gameUserSettings.IsReadOnly = false;
string text = File.ReadAllText(gameUserSettings.FullName); //use the fileinfo you just made rather than make the path again
text = Regex.Replace(text, "^sg[.]ShadowQuality=.*$", $"sg.ShadowQuality={Shadows.Value}", RegexOptions.Multiline); //note switch to interpolated strings
File.WriteAllText(gameUserSettings.FullName, text);
That regex is a Multiline one (so ^ and $ have altered meanings):
^sg[.]ShadowQuality=.*$
start of line ^ (not start of input)
followed by sg
followed by period . (in a character class it loses its "any character" meaning)
followed by ShadowQuality=
followed by any number of any character(.*)
followed by end of line $ (not end of input)
The vital bit is "any number of any character" that can cope with the vlaue in the file being 1, 2, 7, hello and so on..
The replacement is:
$"sg.ShadowQuality={Shadows.Value}"
This is an interpolated string; a neater way of representing strings that mix constant content (hardcoded chars) and variable content. When a $tring contains a { that "breaks out" of the string and back into normal c# code so you can write code that resolves to values that will be included in the string -> if Shadows.Value is for example a decimal? of 1.23 it will become 1.23
You can format data too; calling for $"to one dp is {Shadows.Value:F1}" would produce "to one dp is 1.2" - the 1.23 is formatted to 1 decimal place by the F1, just like calling Shadows.Value.ToString("F1") would
I have searched up how to do this. All I got was removing text based on a index point. I would like to have it setup where it uses a string to remove text, instead of choosing the point.
Something along the lines of
string text1 = "Hello World!";
string text2 = "Hello";
string text3;
void RemoveText()
{
text3 = text1.Remove(text2);
Console.WriteLine(text3);
}
Output:
Console: World!
Is there a method that can remove text by using a string? I was looking at the Microsoft Docs, but the problem is that the string wouldn't have a denfinite spot that need to be removed.
text3 = text1.Replace(text2,string.empty);
If you wanted to get part of a user inputed responce, you would doing something along the lines of
string textToRemove = "set background ";
Console.WriteLine("Type 'set background ' then your color.");
string userInput = Console.ReadLine();
string answer = userInput.Replace(textToRemove, string.empty);
SetBackgroundColor(answer);
First what you want to do is set the text you don't care about/need
string textToRemove = "set background ";
Next you are going to tell the user what to input and get the input
Console.WriteLine("Type 'set background ' then your color.");
string userInput = Console.ReadLine();
We would then have to make a new string without the unnessary text
string answer = userInput.Replace(textToRemove, string.empty);
In this case we are using the input to set the background color. So we would write a function for changing the background color with a string argument for the color the user gave.
SetBackgroundColor(answer);
You could also use an If statment or an for/foreach statment to see if the user's text without the unneccasry text is in an array or list containing strings that are allowed to be used.
I want users to create their own POS print file while following some rules. So I have small Parameters.txt file which can be modified by users. Inside that file there are some strings like this:
<CENTER><BOLD>My Header Text
Just some random no parameters input
from user
Date:<NOWDATE> Time:<NOWTIME>
I want to read everything between <> as string1, and everything that is not inside <> as separated string2.
So <NOWDATE> would be parameter that is recognized by code and inserts Date instead of that string, but Date: would be just some text entered by user which would just be passed to POS printer as string.
Also, users can do something like this:
<CENTER><BOLD>Today<NOWDATE>:<NOWTIME>
So instead of <CENTER> there would be some ESC/POS command inserted, same in place of <BOLD>, but Today would be just passed as normal string without anything changed.
It can be all in one big string, but i need a way to distinguish strings inside <> and outside of <>
I know how to read string inside <>, currently I am playing with this
private static string FindStringInBetween(string Text, string FirstString, string LastString)
{
string STRFirst = FirstString;
string STRLast = LastString;
string FinalString;
int Pos1 = Text.IndexOf(FirstString) + FirstString.Length;
int Pos2 = Text.IndexOf(LastString);
FinalString = Text.Substring(Pos1, Pos2 - Pos1);
return FinalString;
}
But this will only get string inside first <>, and ignore everything else.
Can you recommend best way of achieving this?
At the end i used combination of String.Replace
TempString = TempString.Replace("<CENTER>", Center);
and spliting string when finding that it contain certain combination of characters.
if (TempString.Contains("<="))
{
var _parametar = "<=ReceiptNumber>";
string s = TempString;
int start = s.IndexOf("<=") + 2;
int end = s.IndexOf(">", start);
string _splitResult = s.Substring(start, end - start);
}
I have 3 possible input cases
string input = ""; // expected result: ""
string input = "bar-foo"; // expected result: "foo"
string input = "foo"; // expected result: "foo"
And I have to remove everyting including the first separator char - if exists.
Working approach:
string output = input.Split('-').LastOrDefault();
I want to solve this without Split() - my NOT working approach:
string output = input.Substring(input.IndexOf('-') );
How can I handle the IndexOutOfRangeException / make this code work?
Try to add 1:
string output = input.Substring(input.LastIndexOf('-') + 1);
If there's no - in the input, LastIndexOf returns -1 and so you'll have the entire string.
I've assumed that your are looking for input's suffix, that's why I've put LastIndexOf:
"123-456-789" -> "789"
If you want to cut off the prefix:
"123-456-789" -> "456-789"
please, change LastIndexOf into IndexOf
i think you should use Contains Method to identify - is available or not.
string a = "";
if (a.Contains("-"))
{
string output = input.Substring(input.LastIndexOf('-') + 1);
}
Why not just remove it from the string without checking:
input = input.Replace("-foo", string.Empty);
In C# windows forms application I have strings of different length and format from which I would like to display a preview of the first 25 characters without containing any line breaks of any kind in the preview. The preview string should be followed by " ...".
I have some strings less than 25 chars but they also can contain line breaks or sometimes not. the newline can be like <br>, <br />, /n, /r, /r/n, /n/n or an Environment.Newline like in C#.
With shorter strings I get exceptions because of the TextX.SubString(0, 25) cannot be applied.
What ready function in the framework would do it the best way?
Maybe you have any idea how to solve this.
At the end should be appended the " ...", but since the string is already defined there can't be attached something to it TextX.Append doesn't exist in the content.
It seems, that there's no ready function in a framework, but you can do something like this:
public static String Preview(String value) {
String[] newLines = new String[] { "<br>", "<br />", "\n", "\r", Environment.NewLine };
foreach (String newLine in newLines)
value = value.Replace(newLine, ""); // <- May be space will be better here
if (text.Length > 25)
return value.Substring(0, 25) + "…";
// If you want string END, not string START, comment out the line above and uncomment this
// return value.Substring(value.Length - 25) + "…";
else
return value;
}
...
// Test sample
String text = "abcd<br>efgh\r\r\n\n1234567890zxy\n\n1234567890abc";
String result = Preview(text); // <- abcdefgh1234567890zxy1234…
String text2 = "abcd<br>efgh\r\r";
String result2 = Preview(text2); // <- abcdefgh