修剪Object的最后4个字符

时间:2012-05-07 13:32:34

标签: java string oop object substring

我想修剪第3 (Room Type)和第4(Meal type)列中显示的对象的最后4个字符。在底部我提供了输出样本。您可以清楚地看到第3和第4列最后4个字符是括号中的价格,我想要旅行。

public void showAll()

    {
        String name ="";
        String ID="";
        Object roomItem;
        Object mealItem;
        int roomIn;
        int meal;
        int days=0;
        double tprice=0;

        display.setText("");
        display.append("ID  Customer Name   RoomType    MealType    Days    TotalCharge($)");
        display.append("\n ---------------------------------");

        for (int i = 0; i < myList.size(); i++)
           {
        Customer c = myList.get(i);

        ID = c.getID();
        name = c.getName();
        roomIn = c.getRoomIndex();                  // Get the room index stored in Linked list
        roomItem = roomTypeCombo.getItemAt(roomIn); // Get the item stored on that index.
        meal = c.getMealIndex();                    // Get the Meal index stored in Linked list
        mealItem = mealCombo.getItemAt(meal);       // Get the item stored on that index.
        days = c.getDaysIndex();
        tprice = c.getTotalPrice();
        display.append("\n"+ID+"    "+name+"        "+roomItem+"    "+mealItem+"    "+days+ "   "+tprice);
            }
        display.append("\n \n Total "+myList.size()+" Entrie(s) !");

    } // end of function

我的程序输出是这样的:

ID  Customer Name           RoomType    MealType    Days    TotalCharge
__________________________________________________________________

234 John Andersen       Standard($75)   Any Two($30)     4    420.0

如何查看Room TypeMeal Type的最后4个字符?

3 个答案:

答案 0 :(得分:2)

String pricey = "Breakfast($10)";
String yummy = pricey.substring(0, pricey.length() - 4);

答案 1 :(得分:1)

首先,您应该在发布此类问题之前阅读Java String API:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

然后,您可以使用类似子字符串的方法。

public String substring(int beginIndex,
               int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Examples:

     "hamburger".substring(4, 8) returns "urge"
     "smiles".substring(1, 5) returns "mile"


Parameters:
    beginIndex - the beginning index, inclusive.
    endIndex - the ending index, exclusive.
Returns:
    the specified substring.
Throws:
    IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

答案 2 :(得分:0)

您可以使用substring()

String word = "Breakfast($10)".substring(0, "Breakfast($10)".length() - 4);
相关问题