Is there an elegant job to concatenate?

I am writing a crazy libs program for fun and just programming something. The program itself is fairly straightforward, but I find that I resort to several concatenations due to the nature of the game, where you put the words you entered into the sentence. Is there an elegant job to resort to less grip or even eliminate them for something more efficient? I know, in the end, it doesn't matter if I use concatenation or not, but I'm curious if there is a more elegant way to write this program.

Update: I am using java, but if there is a general solution to speed up concatenation, that will be appreciated too.

+3
source share
11 answers

One solution may be to write your entire crazy libs file and put in special tokens that need to be replaced with the selected words.

You just bought a new $ {NOUN1} and it will be $ {VERB1} you.

Then you can use, for example: String.replace("${NOUN1}", noun1)for all words.

+8
source

What language do you use?

Most higher level langauges will have something similar to:

String.Format("{0} {1} {2} {3}", word1, word2, word3, word4);
+3
source

, :

  • : . , .

  • , , charAt .

+2

, String.replace StringBuilder, String.format( jdk 1.5 newer) MessageFormat.format jdk 1.4. , .

String myPattern = "My %s eats your %s";
// get values from the user here
String result = String.format( myPattern, (Object[])myArray );

String myPattern = "My {0} eats your {1}";
// get values from the user here
String result = MessageFormat.format( myPattern, (Object[])myArray );

, .

public class Format
{
    public static void main( String[] args )
    {
        String pattern = "My %s eats your %s";
        System.out.println( String.format( pattern, (Object[])args ));
    }
}
+2

.

-, . . , .

-, . . - , . .

+1

. , , - , . , , , ,

String x = "Hi";
String y = x + " there!";

Java, StringBuffer, :

StringBuffer myStringBuffer = new StringBuffer();
myStringBuffer.append("Hi");
myStringBuffer.append(" there!");

- . , , .

+1

, Java, , PHP Javascript, , .

Javascript:

var str = str1 + str2 + str3 + "str4" + str5 + "str6" + str7;
var str = [str1, str2, str3, "str4", str5, "str6", str7].join("");

PHP:

$str = $str1 . $str2 . $str3 . "str4" . $str5 . "str6" . $str7;
$str = implode("", array($str1, $str2, $str3, "str4", $str5, "str6", $str7));

, , , .

+1

" " , ? .NET, StringBuilder , .

0

String, , char [] String, , .

0

, , . , , .

, . , .

, , - "% 001 % 002", :

1) , , . 2) "the", " ", 3) - :

PrintStream  = //get output from somewhere
for(int i = 0; i < pieces.size()-1 ; i++){
   ps.print(peices.get(i));
   ps.print(answers.get(i));
}
ps.print(pieces.get(pieces.size()-1));//last one

. , "" . , . , , , -, ..

, , , , , .

, , ByteArrayOutputStream , madlib . .

0

, , . , , , (, "fdsfsd" + var1 + var2 + "dsfsdf" + "tyhty", , ( ). String Builder , .

0

Source: https://habr.com/ru/post/1704806/


All Articles