How to Create a String with Format

How to build a formatted string in Java?

String s = String.format("x:%d, y:%d, z:%d", x, y, z);

Java Howto - Format a string

How to create a String with format?

I think this could help you:

import Foundation

let timeNow = time(nil)
let aStr = String(format: "%@%x", "timeNow in hex: ", timeNow)
print(aStr)

Example result:

timeNow in hex: 5cdc9c8d

Creating C formatted strings (not printing them)

Use sprintf. (This is NOT safe, but OP asked for an ANSI C answer. See the comments for a safe version.)

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text
that would be printed if format was used on printf, but instead of
being printed, the content is stored as a C string in the buffer
pointed by str.

The size of the buffer should be large enough to contain the entire
resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the
content.

After the format parameter, the function expects at least as many
additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer
should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same
specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of
additional arguments, each containing a value to be used to replace a
format specifier in the format string (or a pointer to a storage
location, for n). There should be at least as many of these arguments
as the number of values specified in the format specifiers. Additional
arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");

Format a Go string without printing?

Sprintf is what you are looking for.

Example

fmt.Sprintf("foo: %s", bar)

You can also see it in use in the Errors example as part of "A Tour of Go."

return fmt.Sprintf("at %v, %s", e.When, e.What)

String Format .format to variable

You're overwriting the age string so there's nothing left to format in the second iteration. You could use two strings - one with the template to format in to, and one with the formatted result:

num = 1
template = 'My age is {}'
while num<7:
age = template.format(num)
print(age)
num+=2

How to create a String with String.format by taking parameters from a list

Something like the following using Collectors.joining with mapping as required witht index and answer :

return IntStream.range(0, answers.size())
.mapToObj(idx -> String.format("Q%s = %s", idx + 1, answers.get(idx)))
.collect(Collectors.joining(", "))

How to create a string with format specifier?

As discussed also in this rather similar question, you could use the Boost Format Library. For example:

std::string PrintMyMessage( const string& currentValAsString )
{
boost::format fmt = boost::format("Current value is %s") % currentValAsString;
// note that you could directly use cout:
//std::cout << boost::format("Current value is %s") % currentValAsString;
return fmt.str();
}

In the answers to the other question you can also find other approaches, e.g. using stringstreams, snprintf, or string concatenation.

Here's a complete generic example:

#include <string>
#include <iostream>
#include <boost/format.hpp>

std::string greet(std::string const & someone) {
boost::format fmt = boost::format("Hello %s!") % someone;
return fmt.str();
}

int main() {
std::cout << greet("World") << "\n";
}

Or, if you can't or don't want to use Boost:

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

std::string greet(std::string const & someone) {
const char fmt[] = "Hello %s!";
std::vector<char> buf(sizeof(fmt)+someone.length());
std::snprintf(&buf[0], buf.size(), fmt, someone.c_str());
return &buf[0];
}

int main() {
std::cout << greet("World") << "\n";
}

Both examples produce the following output:

$ g++ test.cc && ./a.out
Hello World!

How to format strings in Java

In addition to String.format, also take a look java.text.MessageFormat. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.

For example:

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });

Generate fixed length Strings filled with whitespaces

Since Java 1.5 we can use the method java.lang.String.format(String, Object...) and use printf like format.

The format string "%1$15s" do the job. Where 1$ indicates the argument index, s indicates that the argument is a String and 15 represents the minimal width of the String.
Putting it all together: "%1$15s".

For a general method we have:

public static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}

Maybe someone can suggest another format string to fill the empty spaces with an specific character?



Related Topics



Leave a reply



Submit