Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format() format for last characters of a string

is there a possibility to set a String.format argument such that the last N characters of the input are used, i.e. something like:

String s = String.format("%1${N}s", "abcdef");

so that s contains "def"? This is common in script languages where you can say

exp = "abcdef"
s = exp[-3]

EDIT

OK, so i don't want to format my data AND handle it when putting it into the String#format function. That's the whole point of the format description here. This format description represents a form of modularity, which is considerably broken if I have to format my input data beforehand although there is a formatter to come...

like image 399
Bondax Avatar asked Sep 24 '12 11:09

Bondax


People also ask

What is string format in Java?

Java String format() The java string format() method returns the formatted string by given locale, format and arguments.

What is string formatting in C?

A String is usually a bit of text that you want to display or to send it to a program and to infuse things in it dynamically and present it, is known as String formatting. There are three different ways to perform string formatting:- Formatting with placeholders. Formatting with.format () string method.

How do you format a string in Python?

Formatting with the.format() string method. This method was introduced in Python 3 was later also introduced to Python 2.7. Formatting is now done by calling.format() method. Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

How do I call the string format method?

However, when calling the String.Format method, it is not necessary to focus on the particular overload that you want to call. Instead, you can call the method with an object that provides culture-sensitive or custom formatting and a composite format string that includes one or more format items.


1 Answers

Unfortunately, even now (y2017) Java 8 Formatter doesn't support "substring".

You can try:

  • Freemarker and slicing (substrings):

    // string 'abcde', evaluates to "bcd"
    <#assign s="abcde">
    ${s[1..3]}
    
  • Spring Expression Language (SpEL) and expressions methods:

    // string literal 'abcde', evaluates to "bcd"
    ExpressionParser parser = new SpelExpressionParser();
    String sub = parser.parseExpression("'abcde'.substring(2, 4)").getValue(String.class);
    
like image 143
kinjelom Avatar answered Oct 23 '22 09:10

kinjelom