¿Cómo convertir CharSequence a String?

5 minutos de lectura

avatar de usuario

¿Cómo puedo convertir un Java CharSequence a un String?

  • Manera más segura: String.valueOf(charSequence). Aquí está la respuesta detallada

    – Minhas Kamal

    5 de noviembre de 2021 a las 7:30

Al invocar su toString() método.

Devuelve una cadena que contiene los caracteres de esta secuencia en el mismo orden que esta secuencia. La longitud de la cadena será la longitud de esta secuencia.

  • @TheOnlyAnil, llama setText(CharSequence) no haces lo que necesitas?

    –Mike Samuel

    4 mayo 2015 a las 20:31

  • @TheOnlyAnil, tal vez deberías hacer eso como pregunta. Los comentarios sobre una respuesta a una pregunta relacionada tangencialmente no son un buen lugar para tratar de descifrar sus requisitos.

    –Mike Samuel

    5 mayo 2015 a las 14:38

  • Al usar el método toString(), mi CharSequence se muestra como “[Ljava.lang.CharSequence;@26ae880a”, not the text that was actually sent. toString() doesn’t work.

    – Joust Knight

    Jul 25, 2018 at 12:41

  • @WillByers that output looks like the toString of a CharSequence array, not a CharSequence.

    – Mike Samuel

    Jul 25, 2018 at 13:45

  • @Hibbem someone else did it for you 😉

    – horcrux

    Jan 28, 2021 at 11:06

user avatar

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method’s javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won’t even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you’ll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
return sb.toString();

  • You shouldn’t make mistakes/make your code worse because others might have made a mistake.

    – Lodewijk

    Apr 18, 2013 at 2:03

  • return new StringBuilder(charSequence).toString(); is a single liner equivalent.

    – Gábor Lipták

    Sep 1, 2015 at 12:48

  • THIS ANSWER IS WRONG The CharSequence interface explicitly defines toString() – the implementor won’t have missed this. The javadoc states “Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence” since inception in 1.4. People, please verify what you upvote

    – earcam

    Apr 16, 2016 at 14:34

  • This is silly. If you don’t trust the implementer to follow the contract, all bets are off. Passing it as a parameter to StringBuilder could just as well fail to do what you expect. The same goes for any other interface, such as List or Set, in particular their equals() and hashCode() methods which will compile without overrides, but must be overridden according to the contract.

    – shmosel

    Jul 29, 2016 at 20:37

  • The fact that the interface does this is arguably a poor decision in that regard, and my answer simply highlights that this is an easier than normal place for human error to occur.

    – fragorl

    Aug 1, 2016 at 1:59

You can directly use String.valueOf()


Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

  • This actually just bit me today. if charSequence is null then the returned string will be "null" and not null.

    – ChrisThomas

    Mar 5, 2018 at 20:31

  • Oh. Makes sense. I will remove this answer

    – Abhishek Batra

    Mar 5, 2018 at 20:38

  • I think this is perfect for some cases.

    – Shukant Pal

    Jan 4, 2019 at 16:08

  • This is quite same as charSequence.toString() looking at the definition in libcore/ojluni/src/main/java/java/lang/String.java public static String valueOf(Object obj) { return (obj == null) ? “null” : obj.toString(); }

    – Padmanabha V

    Jul 20, 2020 at 10:12

user avatar
Minhas Kamal

The Safest Way

String string = String.valueOf(charSequence);

Let’s Dive Deep

There are 3 common ways that we can try to convert a CharSequence to String:

  1. Type Casting: String string = (String) charSequence;
  2. Calling toString(): String string = charSequence.toString();
  3. String.valueOf() Method: String string = String.valueOf(charSequence);

And if we run these where CharSequence charSequence = "a simple string"; then all 3 of them will produce the expected result.

The problem happens when we are not sure about the nature of the CharSequence. In fact, CharSequence is an interface that several other classes implement, like- String, CharBuffer, StringBuffer, etc. So, converting a String to a CharSequence is a straightforward assignment operation, no casting or anything is required. But, for the opposite, Upcasting, it is not true.

If we are sure that the CharSequence is actually an object of String, only then we can use option 1- Type Casting. Otherwise, we will get a ClassCastException. Option 2 and 3 are safe in this case.

On the other side, if the CharSequence is null then option 2, calling toString(), will give a NullPointerException.

Now internally, String.valueOf() method calls the toString() method after doing a null check. So, it is the safest way. JavaDoc:

if the argument is null, then a string equal to “null”; otherwise, the value of obj.toString() is returned.

Please be aware: If CharSequence is null then String.valueOf() method return the string- "null", not null value.

If you want to convert an array of CharSequence,
You can simply do this and can also be store it in a String[] variable.

CharSequence[] textMsgs = (CharSequence[])sbm.getNotification().extras.get(Notification.EXTRA_TEXT_LINES);
if (textMsgs != null) {
   for (CharSequence msg : textMsgs) {
       Log.e("Msg", msg.toString());

avatar de usuario
Arman Arshakyan

También puedes usar Stringbuilder.

new StringBuilder(charSequence).toString();

¿Ha sido útil esta solución?

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos y para mostrarte publicidad relacionada con sus preferencias en base a un perfil elaborado a partir de tus hábitos de navegación. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos. Configurar y más información