Home » Android » Android: Convert first letter of string to lower case

Android: Convert first letter of string to lower case

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’m looking for a way to convert the first letter of a string to a lower case letter. The code I’m using pulls a random String from an array, displays the string in a text view, and then uses it to display an image. All of the strings in the array have their first letter capitalized but image files stored in the app cannot have capital letters, of course.

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);

Thanks!

How to&Answers:
    if (monb.length() <= 1) {
        monb = monb.toLowerCase();
    } else {
        monb = monb.substring(0, 1).toLowerCase() + monb.substring(1);
    }

Answer:

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

Answer:

Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using various CaseFormat conversions.

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
  }

}

Output Like:

STUDENT_NAME
studentName
StudentName
student-name