Question abotu String.format() functionality

Hello all,
I am curious as to whether this functionality exists in the String.format method, or if there is any other class in the current version of Java that would allow for this.
I want to construct a format string, where if one of the args contains a newline character in it, the same format for that arg will be used on the newline.
Example:
String s = String.format("%20s%20s","this line contains\na newline character","so does\nthis one");
System.out.println(s);
Actual Output:
this line contains
a newline character    so does
this one
Wanted Output:
this line contains         so does
a newline character      this oneHopefully there is something that exisits in the language that would allow me to do this. If no one can think of any easy way to do this? I have a few ideas, but it would require a whole lot of string manip. than I want to put into it =(
Anyways, I look forward to your reply. Thanks!

You want the method to treat the strings as multi-line blocks of text instead of as strings? And put the blocks next to each other instead of the strings? Maybe padding the blocks with spaces? Forget it, that's way too complicated for a quick and dirty formatting method.
And yes, a whole lot of string manipulation would be going into that.
Assuming that I understood your requirements correctly. I just went by the picture, I couldn't make any sense out of the words you used to describe it, so I may well be totally wrong.

Similar Messages

  • Pad leading zeros in a string.Format function

    How could use the string.Format function and in the format text pad a leading zero? 
    Pseudo code is:
    string parm = “5”;
    string format = “Some number formatted as 3 dig: Format({0}, 000)”;
    string output = string.Format(format, parm);
    Where the output would look like this:
    “Some number formatted as 3 dig: 005”
    Thanks.

    Thanks everyone. Unfortuantly there's a constraint where the padding operation needs to be embedded in the format string. This entire operatin is being put together dynamically where the format strings are being pulled from a library of format strings stored
    in a database. at runtime we don't know how which format will be used and how many parameters will be passed in. we have logic to handle the unknown number of paramters as there is metadata which helps us with that.
    the need for leading zeros needs to be part of the overall format defined in the format string.  for example, a real format string stored in the database looks like this:
    "LINE_NO = '{0}',  AND GEO_LOCATION = 'T{1}, {2},  R{3}, {4}, , Sec. {5}'"
    and its output from the string.Function is:
    "LINE_NO = 'TG-G2469',  AND GEO_LOCATION = 'T155, N,  R93, W, , Sec. 5'"
    the last parameter (param 5) had a value of 5.  In another case the output requirement might need to look like this:
    "LINE_NO = 'TG-G2469',  AND GEO_LOCATION = 'T155, N,  R93, W, , Sec. 05'"
    note the "05" at the end...
    the logic of using the leading zero needs to be embedded in the overall format string text.
    Thank you.

  • String formatting functions for ASCII Reports in TestSatnd 4.0

    Hi,
    I am trying to create ASCII text reports that shall contain a list of instruments and their parameters in a tabular form (as shown below). Is there any function available for string formatting that is readily available to format the strings in a way that they are alinged in a way to give a tabular look. Using "\t" between the details listed gives a very uneven look.
    Name         Param1        Param2       Param3      Param4       Param5
    Instru1        Xxxx            XXXXXX       X                 XXXXXX        XXX
    Instru 2       YYYYYY      YYYY             YYYYYY    YYY               YYYYYY 
    Thanks
    Saranya
    Message Edited by SaranCh on 04-23-2008 12:32 AM

    You could use Str() to put strings within fixed width columns. Examples for left and right justification:
    "|" + str("MyValue","%-40s")+"|"         
    -->
    |MyValue                                 |
    "|" + str("MyValue","%40s")+"|"         
    -->
    |                                 MyValue|

  • Build string.Format parameters with a loop

    I need to dynamically build the parameters for the string.Format function dynamically in a loop.
    So rather than coding it like this:
    string result = string.Format(formatString, crits[0], crits[1], crits[2], crits[3], crits[4]);
    I need to add the parameters dynamically in a loop like this:
    StringBuilder sb = new StringBuilder();
    formatString = "T{0}{1}-R{2}{3}-{4}";
    sb.Append(formatString);
    foreach (var item in crits)
    // some logic here to determine if this param should be passed in
    sb.Append(", " + item);
    string result = string.Format(formatString);
    Any idea how to do this?
    Thanks.

    No, what you said the other day was to add a column to the table, but the parameters must come from one source and the where clause must come from another source and I have to dynamically mash them together.  the same set of parameters might be used
    with many different syntax in the where clause.
    The output for a where clause might look like this:
    (LINE_NO = 'TG-P1269') AND (GEO_LOCATION = 'T155N R96W, Sec. 10')
    OR
    (LINE_NO = 'TG-G1183') AND (GEO_LOCATION = 'T157N R94W, Sec. 20')
    OR
    (LINE_NO = 'TG-G1182') AND (GEO_LOCATION = 'T157N R94W, Sec. 20')
    OR... etc x 1000
    but to simplify it lets just work with:
    (GEO_LOCATION = 'T157N R94W, Sec. 20')
    which I achieved like this:
    string formatString = "T{0}{1} R{2}{3}, Sec. {4}";
    string result = string.Format(formatString, crits[0], crits[1], crits[2], crits[3], crits[4]);
    However, at run time I don't know how many params to pass in or which ones.  I might have to do this:
    string result = string.Format(formatString,  crits[2], crits[3], crits[4]);
    or this:
    string result = string.Format(formatString,   crits[3]);
    or something else.
    I would be able to determin which params to pass in in the loop, but of course, that's not how the string function works.

  • Questions about user-defined functions

    Hello all,
    I've got some questions about user-defined function in a message mapping:
    1) How can I get the current date/time in format yyyy-mm-dd hh:mm:ss ? What is the java code for this?
    2) I want to use the StreamTransformation constant TIME_SENT, only this is not in the right time-zone.
    It is GMT and it should be CET (1 hour difference). How can I convert this in Java?
    Can somebody help me with this?
    Thanks in advance.
    Kind regards,
    Marco van Iersel

    Hi Marco,
    If the date format is fixed as you have mentioned,please use this:
                                    String test = "2009-03-27 23:15:30";
              String test1 = test.substring(11,13);
              if(!test1.equals("23"))
              int a = Integer.parseInt(test1);
              int b = a+1;
              System.out.println("b"+b);
              String c = Integer.toString(b);
                                    test = test.substring(0,10)+" " + c + test.substring(13,19);
                                    return test;
              if(test1.equals("23"))
              test = test.substring(0,10)+ " 00" + test.substring(13,19);
              return test;
                                    else return "";
    Kindly let me know if this works.
    Thanks.
    Regards.
    Shweta

  • Number to fraction string +format value

    Hi there,
    I just met a stupid question which made me crazy, please help.
    The question is simple:
    Target: Numeric floating control-> number to fraction string -> format value -> desirable string format
    For example: 20.00 -> 20.00000 (Q1: why extra 0s?)-> "20.00"
    I use the following program:
    why doesn't it work, please?
    Thanks!

    Hi TriStones,
    "Why it doesn't work?"
    Because you haven't read the context help for "Number to fractional string"! Especially the sentences on those two additional inputs of that function (Q1)...
    I would suggest using FormatIntoString like that:
    (I tried to replicate your example, but your wiring is very bad: it's not clear which wire is connected to which input...)
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Problem in getting last value of a string in Function Module

    Hi,
    I am working on FM in which i have to put highfen mark which is working ok,but the problem if there is when the value of string finds a space it should not insert highfen in it and i am not able to put the condition in it as it showing the higfen even when the word is full in the first line.i want to show highfen where the word is not able to display complete. here is d code which i am using right now. plzz provide me guidlines to solve this problem.
    here's d code:-
    FUNCTION Z_STRING_LENGTH1.
    *"*"Local Interface:
    *"  IMPORTING
    *"     VALUE(I_STRING) TYPE  STRING
    *"     VALUE(LENGTH) TYPE  I
    *"  EXPORTING
    *"     VALUE(E_STRING) TYPE  STRING
    data: STRING_F type string, "Stores the value in string format
          STRING_LENGTH type i, "Length of the string
          DIFF type i,          "Difference among the value
          DIFF1 TYPE C,
          STRING1 type string,  "Stores the 1st String
          STRING2 type string,  "Stores the 2nd String
          STRING3 type string,  "Stores the 3rd String
          STRING4 type string,  "Stores the 3rd String
          STRING5 type string,  "Stores the 3rd String
          LENGTH2 type I.
    STRING_F = I_STRING.
    STRING_LENGTH = STRLEN( I_STRING ).
    DIFF = STRING_LENGTH - LENGTH.
    IF DIFF LE 0.
      DIFF = 0.
    ENDIF.
    IF LENGTH LE STRING_LENGTH.
      STRING1 = STRING_F(LENGTH).
    ELSE.
      STRING1 = STRING_F(STRING_LENGTH).
    ENDIF.
    IF LENGTH LE STRING_LENGTH.
      STRING2 = STRING_F+LENGTH(DIFF).
    ELSE.
      STRING2 = STRING_F+STRING_LENGTH(DIFF).
    ENDIF.
    length2 = length - 1.
    STRING3 = STRING1+length2(1).
    STRING4 = STRING2+0(1).
    IF LENGTH LE STRING_LENGTH AND STRING3 NE SPACE AND STRING4 NE SPACE.
      concatenate STRING1 '-' STRING2  into STRING5.
      e_string = STRING5.
    ELSE.
      concatenate  STRING1 STRING2 into STRING5.
      e_string = STRING5.
    ENDIF.
    ENDFUNCTION.
    Edited by: ricx .s on May 12, 2009 5:20 AM

    Hi,
    I checked your code... its working fine except for some cases it is giving dumps for which I have added certain if conditions....
    Please check the modified code below... have optimized it as well by removing one extra if condition....
    you can copy and paste the code below...
    DATA: STRING_F TYPE STRING, "Stores the value in string format
          STRING_LENGTH TYPE I, "Length of the string
          DIFF TYPE I,          "Difference among the value
          DIFF1 TYPE C,
          STRING1 TYPE STRING,  "Stores the 1st String
          STRING2 TYPE STRING,  "Stores the 2nd String
          STRING3 TYPE STRING,  "Stores the 3rd String
          STRING4 TYPE STRING,  "Stores the 3rd String
          STRING5 TYPE STRING,  "Stores the 3rd String
          LENGTH2 TYPE I.
    STRING_F = I_STRING.
    STRING_LENGTH = STRLEN( I_STRING ).
    DIFF = STRING_LENGTH - LENGTH.
    IF DIFF LE 0.
      DIFF = 0.
    ENDIF.
    IF LENGTH LE STRING_LENGTH.
      STRING1 = STRING_F(LENGTH).
      STRING2 = STRING_F+LENGTH(DIFF). " added this statement in this if itself instead of one extra if
    " which is not required
    ELSE.
      STRING1 = STRING_F(STRING_LENGTH).
      STRING2 = STRING_F+STRING_LENGTH(DIFF).
    ENDIF.
    IF LENGTH IS NOT INITIAL.
      LENGTH2 = LENGTH - 1.
    ENDIF.
    " put this if condition as there is a dump occuring at this place.
    " Dump occurs when you give the length value as 0
    " Say for example the value of I_STRING, I passed it as SIDDARTH
    " and the length I passed as 0, then it gives me a dump
    STRING3 = STRING1+LENGTH2(1).
    IF STRING2 IS NOT INITIAL.
      STRING4 = STRING2+0(1).
    ENDIF.
    " put this if condition as there is a dump occuring at this place.
    " Dump occurs when you give the length value greater than or equal to
    " the string length
    " Say for example the value of I_STRING, I passed it as SIDDARTH
    " and the length I passed as 8, then it gives me a dump
    IF LENGTH LE STRING_LENGTH AND STRING3 NE SPACE AND STRING4 NE SPACE.
      CONCATENATE STRING1 '-' STRING2  INTO STRING5.
      E_STRING = STRING5.
    ELSE.
      CONCATENATE  STRING1 STRING2 INTO STRING5.
      E_STRING = STRING5.
    ENDIF.

  • Non-numeric String formatting

    Ok, I understand about numeric string formating (NumberFormat). But what I need help with is string formatting.
    For example, I'm working on an app with fixed-length records. Let's take a name field. I need the string "John Doe" formatted to a 40-character field, right-justified. Can someone point me to a class or a URL with information on this.
    Sorry for asking such an elementary question.

    Ok, I understand about numeric string formating
    (NumberFormat). But what I need help with is string
    formatting.
    For example, I'm working on an app with fixed-length
    records. Let's take a name field. I need the string
    "John Doe" formatted to a 40-character field,
    right-justified. Can someone point me to a class or a
    URL with information on this.In the JDK I found nothing, but in the jakarta-Projekt of apache.org:
    http://jakarta.apache.org/commons/lang.html
    There is a class called StringUtils.
    You only have to write:
    String rightJustified = StringUtils.rightPad("John Doe", 40);
    If you don't find something in the JDK look at Jakarta. They have a lot of useful stuff.

  • Is there any String format class available in J2ME?

    Hello,
    I am looking for a Formating class which should format a string. For example ( This is Java SE code):
    int num = 999;
                String str = " is my lucky number.";
                String s = String.Format("The Number : %d %s", num, str);I could not find any formatter class nor any direct api from String/StringBuffer class to format a string.
    Any suggestion on this is highly appreciated.
    Thank You.
    Regards,
    DK

    sojourner_jdk wrote:
    Hi DarrylBurke,
    You are right. Its not "Format". String has "format" function ..
    String s = String.format("The Number : %d %s", num, str);Is there such class/api in J2ME?
    Thanks,
    Regards,
    -DKIn J2ME MIDP, [String has no "format" function|http://java.sun.com/javame/reference/apis/jsr118/java/lang/String.html|javadoc].

  • Input XML Format needs to be Translated Into CSV String Format

    Hi,
    I need to translate input xml format to CSV string format in BPEL.
    How to use xpath function to do this?
    Thanks

    1. In the partner link of the file adapter you can run the wizard and create a XSD according to your CSV format.
    (you just need to create an example of CSV)
    The wizard will create a XSD automatically.
    2. Assign an invoke activity to that partner link.
    3. Use transformation to pass data from your XML input into the invoke variable.
    Arik

  • LabView String StartsWith functionality like in C#?

    Hello all,
    in C# (.NET) there is a good class: String
    There it is possible e.g. to get information, if the string startswith a special substring.
    Is there such possibility in LabView? Is there such LabView vi, which offers this functionality? (Some snippet?)
    Why I am asking:
    I want to create a switch/case-block (case-structure) in labview for this code:
    if(string.startswith("XYZ"))  step into case1
    else if(string.startswith("DEF")) step into case2
    BTW:
    It would be so nice if anybody could create polymorphic VI with these functions: 
    (from C# string class)
    public object Clone();
    public static int Compare(string strA, string strB);
    public static int Compare(string strA, string strB, bool ignoreCase);
    public static int Compare(string strA, string strB, StringComparison comparisonType);
    public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture);
    public static int Compare(string strA, string strB, CultureInfo culture, CompareOptions options);
    public static int Compare(string strA, int indexA, string strB, int indexB, int length);
    public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase);
    public static int Compare(string strA, int indexA, string strB, int indexB, int length, StringComparison comparisonType);
    public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture);
    public static int Compare(string strA, int indexA, string strB, int indexB, int length, CultureInfo culture, CompareOptions options);
    public static int CompareOrdinal(string strA, string strB);
    public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length);
    public int CompareTo(object value);
    public int CompareTo(string strB);
    public static string Concat(IEnumerable<string> values);
    public static string Concat<T>(IEnumerable<T> values);
    public static string Concat(object arg0);
    public static string Concat(params object[] args);
    public static string Concat(params string[] values);
    public static string Concat(object arg0, object arg1);
    public static string Concat(string str0, string str1);
    public static string Concat(object arg0, object arg1, object arg2);
    public static string Concat(string str0, string str1, string str2);
    public static string Concat(object arg0, object arg1, object arg2, object arg3);
    public static string Concat(string str0, string str1, string str2, string str3);
    public bool Contains(string value);
    public static string Copy(string str);
    public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
    public bool EndsWith(string value);
    public bool EndsWith(string value, StringComparison comparisonType);
    public bool EndsWith(string value, bool ignoreCase, CultureInfo culture);
    public override bool Equals(object obj);
    public bool Equals(string value);
    public static bool Equals(string a, string b);
    public bool Equals(string value, StringComparison comparisonType);
    public static bool Equals(string a, string b, StringComparison comparisonType);
    public static string Format(string format, object arg0);
    public static string Format(string format, params object[] args);
    public static string Format(IFormatProvider provider, string format, params object[] args);
    public static string Format(string format, object arg0, object arg1);
    public static string Format(string format, object arg0, object arg1, object arg2);
    public CharEnumerator GetEnumerator();
    public override int GetHashCode();
    public TypeCode GetTypeCode();
    public int IndexOf(char value);
    public int IndexOf(string value);
    public int IndexOf(char value, int startIndex);
    public int IndexOf(string value, int startIndex);
    public int IndexOf(string value, StringComparison comparisonType);
    public int IndexOf(char value, int startIndex, int count);
    public int IndexOf(string value, int startIndex, int count);
    public int IndexOf(string value, int startIndex, StringComparison comparisonType);
    public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType);
    public int IndexOfAny(char[] anyOf);
    public int IndexOfAny(char[] anyOf, int startIndex);
    public int IndexOfAny(char[] anyOf, int startIndex, int count);
    public string Insert(int startIndex, string value);
    public static string Intern(string str);
    public static string IsInterned(string str);
    public bool IsNormalized();
    public bool IsNormalized(NormalizationForm normalizationForm);
    public static bool IsNullOrEmpty(string value);
    public static bool IsNullOrWhiteSpace(string value);
    public static string Join(string separator, IEnumerable<string> values);
    public static string Join<T>(string separator, IEnumerable<T> values);
    public static string Join(string separator, params object[] values);
    public static string Join(string separator, params string[] value);
    public static string Join(string separator, string[] value, int startIndex, int count);
    public int LastIndexOf(char value);
    public int LastIndexOf(string value);
    public int LastIndexOf(char value, int startIndex);
    public int LastIndexOf(string value, int startIndex);
    public int LastIndexOf(string value, StringComparison comparisonType);
    public int LastIndexOf(char value, int startIndex, int count);
    public int LastIndexOf(string value, int startIndex, int count);
    public int LastIndexOf(string value, int startIndex, StringComparison comparisonType);
    public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType);
    public int LastIndexOfAny(char[] anyOf);
    public int LastIndexOfAny(char[] anyOf, int startIndex);
    public int LastIndexOfAny(char[] anyOf, int startIndex, int count);
    public string Normalize();
    public string Normalize(NormalizationForm normalizationForm);
    public string PadLeft(int totalWidth);
    public string PadLeft(int totalWidth, char paddingChar);
    public string PadRight(int totalWidth);
    public string PadRight(int totalWidth, char paddingChar);
    public string Remove(int startIndex);
    public string Remove(int startIndex, int count);
    public string Replace(char oldChar, char newChar);
    public string Replace(string oldValue, string newValue);
    public string[] Split(params char[] separator);
    public string[] Split(char[] separator, int count);
    public string[] Split(char[] separator, StringSplitOptions options);
    public string[] Split(string[] separator, StringSplitOptions options);
    public string[] Split(char[] separator, int count, StringSplitOptions options);
    public string[] Split(string[] separator, int count, StringSplitOptions options);
    public bool StartsWith(string value);
    public bool StartsWith(string value, StringComparison comparisonType);
    public bool StartsWith(string value, bool ignoreCase, CultureInfo culture);
    public string Substring(int startIndex);
    public string Substring(int startIndex, int length);
    public char[] ToCharArray();
    public char[] ToCharArray(int startIndex, int length);
    public string ToLower();
    public string ToLower(CultureInfo culture);
    public string ToLowerInvariant();
    public override string ToString();
    public string ToString(IFormatProvider provider);
    public string ToUpper();
    public string ToUpper(CultureInfo culture);
    public string ToUpperInvariant();
    public string Trim();
    public string Trim(params char[] trimChars);
    public string TrimEnd(params char[] trimChars);
    public string TrimStart(params char[] trimChars);
    Eugen Wiebe
    Bernstein AG
    CLAD - Certified LabView Associate Developer
    Solved!
    Go to Solution.

    Why I am asking:
    I want to create a switch/case-block (case-structure) in labview for this code:
    This can be done already with the case structure, you can do simple parsing in the case selector, which takes a string as an input.
    Type into the case for first case "XYZ....XYZ~"
    Type into next case "DEF...DEF~"
    Next case is empty string, default.
    How does this work:
    The "XYZ...XYZ~"  matches all strings that start with XYZ and have any ascii value after the ~ is the highest printable 7bit ascii value so this catches all other characters.
    Option 2 is parse (there are very good reg expression vi in the string palette) the string and create interger value if a matched then habdle the unique integers in the case structure.
    There are so many ways to do it without making a wrapper for the .net string class, I provided a few quick methods
    Paul Falkenstein
    Coleman Technologies Inc.
    CLA, CPI, AIA-Vision
    Labview 4.0- 2013, RT, Vision, FPGA

  • String-formatting markup search

    The properties for string formatting are many and could support a parsing function that would take a string containing markup and produce a formatted string.  Has anyone done this or know of any code available to implement this?
    I would like to be able to write a string like this:
    <color: red><b>Error: </b></color>An error occured. Please check all <i>cable connections</i>.
    and produce a display like this:
    Error:  An error occurred.  Please check all cable connections.
    Which markup language to use is TBD.  Just looking for starters.

    Well, in fact, that is a great idea and exactly what I hope to do.    I just am wondering if somebody has already done it.

  • [WPF] TextBox and String Format Hour:Minutes

    Hi,
    I would set the string format in a TextBox that it is binding with a Date.
    For example, if I have 01/04/2015 16:11,
    1) I would show only 16:11
    2) When the user modifies the hour must respect the format hh:mm
    Thanks.

    Please close your previous threads by marking helpful posts as answer before you start a new one.
    If the source property is a DateTime you could use the StringFormat property of the binding:
    <TextBox Text="{Binding Date, StringFormat=hh:mm}"/>
    >>When the user modifies the hour must respect the format hh:mm
    A TextBox is only a textBox where the user can type in some text. If you want to restrict the format of the input you could use a masked TextBox. There is no such control built-in into WPF but the WPF Toolkit contains one that you can use:
    https://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox
    Please remember to mark helpful posts as answer to close your threads and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

  • How to check the current time with a Stored  time in string format

    Hi All
    I would like to compare the system time with an existing time values which is allready there in String format..
    i mean i would like to check if the SysTime is inbetween 6:30 and 14:00
    I accomplished this in Oracle ..
    Select 'Y' from dual where to_date(to_char(sysdate,'HH24:MI '),'HH24:MI') between to_date('06:30','HH24:MI') and to_date('14:00','HH24:MI')
    But instead of checking the DB each and every time , the perfomance would be better if we can do this in our java code..
    Could some one provide me with a code to accomplish the above scenario..
    Thanks in advance..,.,

    import java.util.Calendar;
    Calendar rightNow = Calendar.getInstance();  // gets the current date and time to millisec
    Calendar earlyTime = Calendar.getInstance().set(Calendar.HOUR_OF_DAY, 6).set(Calendar.MINUTE, 30);
    Calendar lateTime = Calendar.getInstance().set(Calendar.HOUR_OF_DAY, 8).set(Calendar.MINUTE, 0);
    if (rightNow.compareTo(earlyTime)> 0 && rightNow.compareTo(lateTime) < 0){
    // do something
    }Try this.

  • How to read from a xml file(in String format) using a java program

    hi friends
    i have a string , which is xml format. i want read the values and display it.can any one suggest how to read a xml file of string format using a javaprogram
    thanks

            final DocumentBuilder db =  DocumentBuilderFactory.newInstance().newDocumentBuilder();      
            final InputStream documentStream = new ByteArrayInputStream(documentXMLSourceString.getBytes("utf-8"));
            final Document document = db.parse(documentStream);

Maybe you are looking for