C# appending string from variable inside double quotes - c#

Hi I have the following line:
var table = #"<table id=""table_id"" class=""display"">
which is building a table and continues on the next line but I'm just trying to append a string at the end of table_id :
var table = #"<table id=""table_id" + instance + """ class=""display"">
so the final output (if instance = 1234) should be:
<table id="table_id1234" class="display">
But I think the quotes are throwing it off. Any suggestions on how t achieve the last line?
Thanks

A string.Format method placeholder is enough to concatenate instance without cutting through quote signs ({0} is the placeholder):
var table = string.Format(#"<table id=""table_id{0}"" class=""display"">", instance);
Or you can use escape sequence \" for escaping quotes without string literal:
var table = "<table id=\"table_id" + instance + "\" class=\"display\">"
Result:
<table id="table_id1234" class="display">
Demo: .NET Fiddle

Try to use escape character for double quote(\") using this code:
var id = "1234";
var table = "<table id=\"table_id" + id + "\" class=\"display\">";
Here is an online tool for converting string to escape/unescape:
https://www.freeformatter.com/java-dotnet-escape.html
So you can copy the result and place your variables.

I think the best idea and newest idea for this situation is $ sign before your text and with this sign you dont need to extra sign in your string
example
vat table = $"<table id='table_id{instance}' class='display'">

# is used to escape double quotes from one string but in your example, you are actually concatenating three different strings, soyou should escape the third string as well like this:
var table = #"<table id=""table_id" + instance + #" "" class=""display"" >";
Alternatively, you could also use the StringBuilder class which is more memory efficient and might make your strings easier to read.

Related

Add double quotes to a list to display in a label

Morning folks,
I have an ASP.Net C# page that pulls in a list of servers from a SQL box and displays the list of servers in a label. ("srv1,srv2,srv3"). I need to add double quotes around each of the servers names. ("srv1","srv2","srv3",)
Any help would be greatly appreached.
If you have string
string str = "srv1,srv2,srv3";
Then you can simply do
str = "\"" + str.Replace(",", "\",\"") + "\"";
Now str contains "srv1","srv2","srv3"
As far as I can understand, you are trying to use double quotes in a string.
If you want to use such,
you can use escape character:
("\"srv1\",\"srv2\",\"srv3\"",)
for the sake of simplicity, you can even convert it to a function:
private string quoteString(string serverName){
return "\"" + serverName + "\"";
}
Also, if you have already "srv1,srv2,srv3" format, find ',' characters in the string and add " before and after comma. Also, notice that you should add to first index and last index ".

I need to replace : with ":" form the string "AAAA:123346hadhdhajkkd890" result like "AAAA":"123346hadhdhajkkd890" using Replace functionality in C#

I need to replace the string "AAAA:123346hadhdhajkkd890" with "AAAA":"123346hadhdhajkkd890" using the Replace function in C#.
Hi try to use the code below :
var str = "AAAA:123346hadhdhajkkd890";
str = str.Replace(":", "\":\"");
in order to put " in Replace function you have to use \" in the parameter.
var s1 = "AAAA:123346hadhdhajkkd890";
var s2 = str.Replace(":", "\":\"");
This is because \" will actually tell the compiler " and if simply " will mean the end of the string. This is known as the escape sequence.

Incrementer not working inside string replace

I'm attempting to read a line from a file (csv header) and create a column list that prepends "c[num]_" in front of each column with this code:
int colCount=0;
string line = "col1,col2,col3,col4,col5";
string ColumnList = "([" + (++colCount).ToString() + "_" + line.Replace(",", "],[c" + (++colCount).ToString() + "_") + "]";
I know it's not elegant, but I'm also not sure why my colCount variable doesn't increment inside the replace?? It results with a string like:
([c0_col1],[c1_col2],[c1_col3],[c1_col4],[c1_col5])
The counter increments the first time and then not again inside the replace. Any insights? I think it might be better written with a Regex ReplaceEvaluator but I haven't been able to piece that together yet either.
The paramter of the Replace method is string, and the expression you've entered there is just a string. The count will always be 2. It's not a Func, it a string.
You can use the following Linq to easily achieve the conversion you'd like:
string ColumnList = string.Join(",", line.Split(',').Select((s, i) => $"[c{i + 1}_{s}]"));

Double quotes in a string C#

I'm trying to read through a file and look for this tag
,<table name="File">,
i've read a bunch and everyone tells me to use #""" or \" to accept the double quotes in the middle of the string, but what it does is turns my string into this. <table name=\"File\"> and it still doesn't work because thats not how it is in the file. examples:
string tblName = " <table name="+#"""File"""+">";
string tblName = " <table name=\"File\">";
Nothing seems to work. It just addes the \ into the string and i can't replace it because it removes the quotes. Any suggestions?
Thanks
string tblName = " <table name="+#"""File"""+">";
try
{
// Only get files that begin with the letter "c."
string[] dirs = Directory.GetFiles(#"C:\Users\dylan.stewart\Desktop\Testing\", "*.ism");
//Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
foreach (string dir in dirs)
{
foreach( string line in File.ReadLines(dir))
if(line.Contains(tblName))
{
Console.WriteLine(dir);
}
//Console.WriteLine(dir);
}
}
The above methods for adding " into a string are correct. The issue with my OP is i was searching for a specific amount of white space before the tag. I removed the spaces and used the mentioned methods and it is now working properly. Thanks for the help!
string tblName = "<table name=" + '"' + "File" + '"' + ">";
should work since the plus sign concatenate
It should be either
string tblName = #" <table name=""File"">";
or
string tblName = " <table name=\"File\">";
No need for concatenation. Also what do you mean "it still doesn't work"? Just try Console.Write() and you'll see it ok. If you mean the backslashes are visible while inspecting in debugger then it's supposed to be that way
B

How to insert apostrophe in the middle of string using string.Insert c#

I have a bunch of string which i loop through . I want to insert an apostrophe when ever an apostrophe in any string that has apostrophe. I simply do something like below.
string strStatus = "l'oreal";
index = strStatus.IndexOf("'");
strStatus.Insert(index, " ' ");
I want to have output like l''oreal. Yet this fails. I tried using escape patter
strStatus.Insert(index, " \' ");
All to no avail. Please how do i achieve this? Any suggestion/help is highly appreciated.
Strings are immutable. Insert returns a new string with the 2 apostrophes, it doesn't modify strStatus in any way. Your code simply discards the result of Insert.
You should try:
string strStatus = "l'oreal";
index = strStatus.IndexOf("'");
string newStatus=strStatus.Insert(index, "'");
Strings are immutable in .NET (and Java), which means Insert does not modify strStatus, instead it will return a new instance which has the modification you're after.
Do this:
String status = "L'Oreal";
status = status.Insert( status.IndexOf('\''), "'" );
Strings are immutable in C#, so all it's methods do not modify the string itself - they return modified copy. This should work:
strStatus = strStatus.Insert(index, " ' ");

Categories