2011-09-23 211 views
7

我正在尋找將字符串的第一個字母轉換爲小寫字母的方法。我正在使用的代碼從數組中隨機抽取一個字符串,在文本視圖中顯示該字符串,然後使用它顯示圖像。當然,數組中的所有字符串都有大寫字母,但存儲在應用程序中的圖像文件不能有大寫字母。Android:將字符串的第一個字母轉換爲小寫

String source = "drawable/" 
//monb is randomly selected from an array, not hardcoded as it is here 
String monb = "Picture"; 

//I need code here that will take monb and convert it from "Picture" to "picture" 

String uri = source + monb; 
    int imageResource = getResources().getIdentifier(uri, null, getPackageName()); 
    ImageView imageView = (ImageView) findViewById(R.id.monpic); 
    Drawable image = getResources().getDrawable(imageResource); 
    imageView.setImageDrawable(image); 

謝謝!

回答

15
if (monb.length() <= 1) { 
     monb = monb.toLowerCase(); 
    } else { 
     monb = monb.substring(0, 1).toLowerCase() + monb.substring(1); 
    } 
+0

簡單有效!謝謝 – cerealspiller

8
public static String uncapitalize(String s) { 
    if (s!=null && s.length() > 0) { 
     return s.substring(0, 1).toLowerCase() + s.substring(1); 
    } 
    else 
     return s; 
} 
2

谷歌番石榴是一個Java庫與大量的實用工具和可重用的組件。這需要庫guava-10.0.jar在類路徑中。以下示例顯示使用各種CaseFormat轉換。

import com.google.common.base.CaseFormat; 

public class CaseFormatTest { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 

    String str = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "studentName"); 
    System.out.println(str); //STUDENT_NAME 

    str = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "STUDENT_NAME"); 
    System.out.println(str); //studentName 


    str = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "student-name"); 
    System.out.println(str); //StudentName 

    str = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "StudentName"); 
    System.out.println(str); //student-name 
    } 

} 

輸出一樣:

STUDENT_NAME 
studentName 
StudentName 
student-name 
相關問題