A list of puns related to "String Concatenation"
After waiting for 55 minutes using text+= 137k times in a loop, I have googled c# performance one string vs multiple string variables. Although I have not found the answer, this article made me think that I should first try another method before creating a lot of temp variables:
https://dotnetcoretutorials.com/2020/02/06/performance-of-string-concatenation-in-c/
Update: I have just replaced all string+= with StringBuilder.Append. It is now all done in 1.243 second. Yay. Thanks to all recommending StringBuilder
I'm using Visual Studio 2022, and I get error in an app using .NET 6 preview 6 and 7,
string name = "Boar";
string lastname = "of Gold";
// This is right
Console.WriteLine(
$"{name}, " +
$"{lastname} ||");
// This is not
Console.WriteLine(
$"{name}, " +
$"{name}, " +
$"{lastname} ||");
Console.ReadKey();
Output:
Boar, of Gold ||
, Boar, Boar ||of Gold
This code worked fine in Visual Studio 2019 and .NET 5
Is anyone having the same problem?
Hi Folks
I need some help regarding a little task that I have on hand. I am very new to scripting and have been trying to fix this from a few days now so any help will be appreciated.
So, basically I have a shell script that looks like below (simplified) -
#!/bin/bash
b=$1
a=$($b -w '@curl-format.txt' -o /dev/null -s)
echo $a
For variable b, that I will pass is a curl command that will look like this -
# ./test.sh "curl -X POST '
https://example.com/actions/
sample' -H 'cookie: SessionId=me76tt7cfpokm11k7uug1lfoi8' -d 'action=PRIVACYHIDE&redirect=simplified'"
Also, the curl-format.txt file looks like this -
# cat curl-format.txt
{"time_total": %{time_total}}
So the idea is that I have to use this shell script to be able to find total time taken for the curl request to be processed by the server. The trouble I am having is that the curl request fails when typed in the above format. Whereas, simple request like this works fine because I suppose the issue is with the string concatenation and quotes-
# ./test.sh "curl
google.com
"
This runs fine.
Any help would be very much appreciated. I know I am only missing on a tiny bit but this has taken so much time yet I am unable to resolve this simple issue.
Thank you
I am trying to concatenate a string sequentially with the use of a nested for loop:
for(var i=0; i<oggt.length; i++){
var customPopup = "<b>" + oggt[i].nome_caso + "</b><br>";
for(var j = 0; j<oggt.length; j++){
if(oggt[i].codice_identificativo === oggt[j].codice_identificativo &&
oggt[i].codice_identificativo > 0){
customPopup = customPopup + "<div>" + oggt[j].nome_criminale +
"</div>";
}
}
}
CustomPopup should be concatenated two times, and in the string should be two div's, containing oggt[j].codice and oggt[j+n]; but it prints only one div containing oggt[j+n], and the rest is forgot. Where am I wrong? Notice that the output must happen once the j loop is terminated
hello, i have this line in my program
table_template_clone.getElementById('album-image').innerHTML =
`<div><button class="btn" onclick='download("${song_name}", "${artists_names}")'><img src=${album_image} valign="middle" vspace="5" hspace="5" /></button></div>
`
the problem is whenever the song_name
has a ' or " my program crashes i have tried using String.raw but had no luck. pls help
i found the following snippet of code .
#define f(g,g2) g##g2
main() {
int var12=100;
printf("%d",f(var,12));
}
I understand that this will translate f(var,12) into var12 .
My question is in the macro definition, why didn't they just write the following :
#define f(g,g2) gg2
why do we need ## to concatenate text, rather than concatenate it ourselves ?
I just read this article about Schlemiel the Painter and string concatenation.
But I'm struggling to understand the connection.
Schlemiel gets fewer and fewer dots painted because he is constantly having to go back to his paint can, which was left where he started, to get more paint on his brush.
When concatenating strings using something like:
string a = "a";
for(int i = 0; i < 100; i++)
{
a += "a";
}
It will create a new string each time, copying in the original string and the new "a".
But when Schlemiel paints the dots, each dot is further away from the can, however each string concatenation is just copying two strings into a new string, which should taken the same amount of time regardless of how long the strings are, right?
Or do I have a misunderstanding of the time required to concatenate larger and larger strings?
string_array = ["abc", "de" + "fg"]; %works fine
string_con = "de" + "fg"; %works fine
string_array2 = ["abc", "de" +"fg"]; %throws error (why?)
string_con2 = "de" +"fg"; %works fine
So apparently the whitespace between + and a string matters but only within an array. Why is that?
In most languages that support OOP the '.' is used to access members and methods. If a class (say class A) has a method that returns an object of type A, could a language provide an assignment operator .= such that object .= next()
is equivalent to object = object.next()
(similar to += and *= assignments)? It could be used in linked lists algorithms, for example.
Is there any language that implements this feature?
What would be the disadvantages of implementing this operator in a toy language (except the fact that most of the times it is useless)?
Hi, I am trying to do some concatenation to get the url that is directly related to the uploaded videos of a youtube channel. I am getting the youtube links through an excel file which I used a While Loop to parse through each row as a variable $row. Apparently, the string "/videos" gets appended to the front of the url instead of the back when I try to concatenate it. The end result I am aiming to get is "youtube.com/channelabc/videos" but I can't seem to get it done for some reason.
Could anyone please help me out with this? I have spent quite some time on this already ><
Edit: Thanks everyone for helping out! Truly appreciate it!! 🙏
Looking for some help on my program. Creating a program that is working with strings being concatenated. When outputted I'm trying to get a space between both string fullName && string firstName.
ISSUE: strcat_s (fullName, lastName);
current output = Tommy LeeJones
desired output = Tommy Lee Jones
#include <iostream>
#include <string>
#include <cstring>
#include <string.h>
using namespace std;
int main() {
char firstAndMiddle[20];
char lastName[20];
char fullName[40];
string friendsName;
cout << "Enter your first and middle names: ";
cin.getline(firstAndMiddle, 20);
cout << "Enter your last name: ";
cin.getline(lastName, 20);
strcpy_s(fullName, firstAndMiddle);
strcat_s(fullName, lastName);
cout << "How is your love life " << fullName << "? ";
cout << "By the way, your full name has " << strlen(fullName) << " characters.\n";
cout << "\nEnter your friends full name: ";
getline(cin, friendsName);
cout << "How is " << friendsName << " love life " << firstAndMiddle << "?";
cout << "By the way, your friends full name has " << friendsName.length() << " characters.\n";
system("pause");
return 0;
}
/*
OUTPUT
Enter your first and middle names: Tommy Boy
Enter your last name: Da VinciHow is your love life Tommy Boy Da Vinci?
By the way, your full name has 18 characters.
Enter your friend’s full name: Tiger WoodsHow is Tiger Woods love life Tommy Boy?
By the way, your friend’s full name has 11 characters.
Press any key to continue ...
*/
output bellow is how my program is suppose to look
Hello!
I just want to vent a bit about a new project I was assigned to. We are helping a client to finish building a Django web.
Now I'm working on fixing some dropdowns, tables and how they list data. Sure, that task is pretty basic. However, I have to search and dig through 500-1000 (they feel that long at least) character long lines of concatinated strings of jquery like +, "<td>$value.name</td>" + $(...)"' ' + value[0].name + "... I think you get what I mean. To me this is very messy to read and a nightmare compared to Vue or Angular.
Now I'm also visually impaired which ofcourse doesn't help. But I use the search functionality and a screen reader to help.
Also, there is no documentation on where I can open the damn modals and check in the browser that I didn't mess anything up. Since this is a client's code base I don't kmow it very well.
Btw, I'm not used to jquery at all. So maybe that contributes a bit to my frustration.
But do you people and normally sighted find that kind of code frustrating and annoying to work with?
Phew.
Thanks!
I'm trying to learn, I'm not from strong typed language so I realized I have no idea how to handle this case and I don't even know what to search for. Please if you can help me I'd be very grateful.
My example is a simple game, let's say it has 30 levels, only 1 level is active at a time (loaded and used), every Level is a separate class such as: Level0, Level1, Level2, ...
When loading a specific Level(n) class I can type a long switch statement based on the integer n and have a code such as:
case i == 0:
Level0 myLevel = new Level0();
break;
case i == 1:
Level1 myLevel = new Level1();
break;
... and so on.
Tree looks like this for classes: Level class (Parent class which also inherits from a general kind of class called Node) -> Level0 class (children of Level) -> Level1 class (children of Level) ...
Level : Node
-> Level0 : Level
-> Level1 : Level
I was wondering if there is some technique or way in c# that would allow me to do this:
var myLevel = (Level + n) new Level(); <-- "Level + n" would work the same as string concatenation.
Or if I have to type super long switch statement for this?
Level share some similar methods but insides of these methods are different obviously, they have different fields (same same, most different).
I read something about interfaces and casting into an interface ILevel which is implemented on a parent Level class something like this:
var my Level = (ILevel) new Level();
But I really have no idea how this works. I read ton about this and my poor brain still can't grasp how this would work.
Parent class Level : Node, ILevel ?
Level0 : Level? Level0 : Level, ILevel?
But then I have no idea how I'd access Node methods, ... inside Level0 if Level0 is cast as ILevel, or how to access fields from Level0 if it's again still cast as ILevel.
I'm really sorry if there is something simple about this and I'm too stupid to understand I spent 2 days on this and I feel dumber and dumber. :0
Thank you very much, I would really appreciate help with this.
In thinkpython 2, a programming learning book, there is this question asked at the end of part 2.6 String operations.
Does somoene now the answer(s)?
Hello Everyone !
I tried to use string concatenation in below code, but i don't get the space between the two strings. Could you guys let me know what is the way to get the space between the two strings.
myName=input()
print ( 'Thanks for the feedback,' + str(myName) + 'we will look at this')
What i am getting - Thanks for the feedback, wolverinewe will look at this.
What is supposed to be - Thanks for the feedback, wolverine we will look at this.
Currently learning python as a new programmer. What are the best use cases for each syntax, and do companies prefer one over the other?
Hello Everyone,
I'm trying to generate SAMaccountname based on my organization standard by taking the values from CSV file. I just started learning PowerShell.
First 4 letters from Lastname: Rooney
First 2 letters from the first name. Wayne
And there will be a column in CSV file with the header "employee type" If it is set to Fulltime, the account should have letter U at the beginning and anything else, it should have V.
VROONWA - e.g for other types of emloyee
UROONWA - E.g for full-time employees. I tried using join string and concatenate string,
$adusers.firstname $adusers.lastname $ADUsers = Import-csv "E:\thiru\Automation\sampleinput.csv" $adusers.lastname.substring(0,4) $adusers.firstname.substring(0,2) [string]::join('',$($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2))) [string]::Concat($($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2)))
I got the below message
PS C:\Windows\system32> [string]::Concat($($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2))) System.Object[]System.Object[] PS C:\Windows\system32> [string]::join('',$($adusers.lastname.substring(0,4)),$($adusers.firstname.substring(0,2))) System.Object[]System.Object[] PS C:\Windows\system32>
Can someone guide me on how to achieve this?
Solution: I should've posted more code, your comments made be look critical at all my variables again. Above the echos it looked like this:
$styles = $this->getBlockStyles(); //returns an array with classname, styles and childStyles, or false
if(!$styles) return false;
extract($styles); //get $classname, $styles, $childStyles
Inspired from JS destruction I tried extract
for the first time. If I change the first line to $data = $this->getBlockStyles();
no crashes occur anymore. So it seems like the double use of $styles
caused the problems. This still does not explain all the super weird behaviour, but I guess reusing variables is just bad.
Edit 2: isolated the "bug" here with annotations: https://pastebin.com/Fgs8ZnDU
Edit: this is happening on a WAMP server. I tested the same code on Debian and there it is not crashing. Weird? 🤔 Any tips for debugging still welcome!
Original Post:
Hey, I just spend multiple hours tracing down a very weird bug that apparently I cannot reproduce in an isolated script and cannot make sense of. I'm collecting CSS styles in an array and then loop over and echo them. This is breaking my site with an ERR_CONNECTION_RESET
message:
foreach($styles as $style) {
echo $classname .' '. $style;
}
While this is working fine:
foreach($styles as $style) {
echo $classname;
echo ' ';
echo $style;
}
Nothing in the php error logs, just the Browser Message ERR_CONNECTION_RESET
after 2-5 seconds. Both variables are strings and not empty.
I think it's not even the echo, when I try to use the frameworks log method in the loop, I get a ERR_CONNECTION_RESET
, too. ($log->message('WTF?');
). Outsite the foreach logging is working. Normally, I get nice errors with XDebug. How could I debug such weird behaviour?
This is all happening in three nested foreach
loops. It's really not a big site and no big data, the style arrays have 7 entries at max. I found a solution with the separate echos but it's driving me crazy. PHP 7.2.4
Definitely a dumb moment and I'm not getting the picture here.
Since C# has operator overloading, I assumed the class definition (in metadata in VS) would have the + operator overloaded as it has for == and !=
public static bool operator ==(String a, String b);
public static bool operator !=(String a, String b);
But I think these are overloaded in the System.String class definition only because the default behaviour of == and !=(that are defined and built into the language) is for reference comparison.
And the reason + operator is not overloaded is because it is built into the language for strings. Am I correct?
If so, is there any way to view the definition/declaration of these operators for their respective classes. The metadata I can see in VS for a particular type only has the properties, methods, etc but not the operators I can use with that type.
What I want is similar to Template Strings in Javascript. I would like to embed functions within the text of a cell and have those functions evaluated.
Having functions be called and evaluated inline would also allow me to easily format the actual text (ie. change the font size, bold some things, break into new lines, etc) without having to format the text through code, which is what concatenation would force me to do, I think.
String concatenation has a number of problems, the number one being that it's then difficult to format the text through the GUI (for example, you can't just select "Blablabla" and hit the Bold icon at the top to make the text bold), because the text is now part of a function since you added "=" to the start of the cell.
Another example: I don't want the contents of my cell to look like "="foo"&char(10)&"bar" just to get "foo" and "bar" to appear on new lines.
The product of column A is '=PRODUCT(A:A)' and the sum of column B is '=SUM(B:B)'. | |||
---|---|---|---|
Output of Above: The product of column A is 10 and the sum of column B is 15. | |||
A | B | ||
1 | 5 | 8 | |
2 | 2 | 7 |
I am not quite sure which way is the best so i wanted to ask this great community...
string.Concat
StringBuilder
string interpolation
I am probably making a silly mistake but I can't figure this out. I have a variable composed of a string and another variable. I'd like the new variable to contain the string data surrounded by double quotes.
>"myid as8832990"
For some reason I get an extra single quote added.
>'"myid as8832990"'
token = "as8832990"
newvar = "myid" + " " + token
quotevar = "\"newvar\""
Or
quotevar = f'"{newvar}"'
I've even tried to remove the single quotes.
removesingle = quotevar.replace("'", "")
But the single quote remains.
'"myid as8832990"'
I know this is probably something pretty stupid on my part. Any help would be appreciated!
void my_strcat(char dest[], char src[]) {
//find out the number of characters in dest
int count = 0;
while (dest[count] != '\0') {
count++;
}
//count is the number of characters in dest
for (int i = 0; src[i] != '\0'; i++, count++) {
//at this point count is total number of characters in BOTH strings
dest[count] = src[i];
}
dest[count] = '\0';
}
I'm rather confused at dest[count] = src[i]. What exactly does this line do? If i'm not wrong at this point count should be the total number of characters in BOTH strings, i is the number of characters in src. How exactly does that line make the strings concatenate?
Hi Folks
I need some help regarding a little task that I have on hand. I am very new to scripting and have been trying to fix this from a few days now so any help will be appreciated.
So, basically I have a shell script that looks like below (simplified) -
#!/bin/bash
b=$1
a=$($b -w '@curl-format.txt' -o /dev/null -s)
echo $a
For variable b, that I will pass is a curl command that will look like this -
# ./test.sh "curl -X POST 'https://example.com/actions/sample' -H 'cookie: SessionId=me76tt7cfpokm11k7uug1lfoi8' -d 'action=PRIVACYHIDE&redirect=simplified'"
Also, the curl-format.txt file looks like this -
# cat curl-format.txt
{"time_total": %{time_total}}
So the idea is that I have to use this shell script to be able to find total time taken for the curl request to be processed by the server. The trouble I am having is that the curl request fails when typed in the above format.
Some of the error that comes is this -
* Protocol 'https not supported or disabled in libcurl
Whereas, simple request like this works fine because I suppose the issue is with the string concatenation and doubling of quotes-
# ./test.sh "curl
google.com
"
This runs fine.
Expected result is like below for example-
{"time_total": 0.012}
Any help would be very much appreciated. I know I am only missing on a tiny bit but this has taken so much time yet I am unable to resolve this simple issue.
Thank you
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.