How to convert CharSequence to String?

165,416

Solution 1

By invoking its toString() method.

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.

Solution 2

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());
sb.append(charSequence);
return sb.toString();

Solution 3

You can directly use String.valueOf()

String.valueOf(charSequence)

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.

Solution 4

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.

Solution 5

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());
   }
}
Share:
165,416

Related videos on Youtube

Belgi
Author by

Belgi

My name is Amir Belgi. I welcome you to visit my blog: https://thetightlycoupled.wordpress.com

Updated on January 25, 2022

Comments

  • Belgi
    Belgi over 2 years

    How can I convert a Java CharSequence to a String?

  • Lodewijk
    Lodewijk about 11 years
    You shouldn't make mistakes/make your code worse because others might have made a mistake.
  • Mike Samuel
    Mike Samuel about 9 years
    @TheOnlyAnil, does calling setText(CharSequence) not do what you need?
  • TheOnlyAnil
    TheOnlyAnil about 9 years
    I want to make actionBar title clickable.
  • Mike Samuel
    Mike Samuel about 9 years
    @TheOnlyAnil, maybe you should ask that as a question. Comments on an answer to a tangentially related question are not a good place to try and tease out your requirements.
  • TheOnlyAnil
    TheOnlyAnil about 9 years
    Stackoverflow won't let me post any question. :/ btw I did that last night. Custom actionbar is the solution :)
  • Gábor Lipták
    Gábor Lipták almost 9 years
    return new StringBuilder(charSequence).toString(); is a single liner equivalent.
  • earcam
    earcam about 8 years
    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
    earcam about 8 years
    Incidentially StringBuilder implements CharSequence, so you're now trusting the StringBuilder implementer did their job properly ツ
  • fragorl
    fragorl about 8 years
    The difference being, it's relatively simple to inspect StringBuilder.java and satisfy yourself that StringBuilder.toString() is doing the correct thing (it is), while it's another matter to verify it is true for the limitless number of custom CharSequence implementations that do or could exist.
  • shmosel
    shmosel almost 8 years
    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.
  • fragorl
    fragorl almost 8 years
    Sure, I agree. However this is more about how the interface actually hijacks the toString() method and usurps its original purpose entirely. Consider the documentation on the base method: "In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read." The intent of toString() is to provide a human-readable representation of an object, not a core piece of programmatic functionality.
  • fragorl
    fragorl almost 8 years
    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.
  • Pavlus
    Pavlus almost 7 years
    @shmosel in fact, an implementer is following interface contract, it implements given method to represent the object as a string, the problem is with its representation that sometimes has nothing to do with CharSequence, but description of the object (try adding CharSequence interface to the ArrayList<Char>, for example, you'll have default implementation of toString(), but it's not the one you want to have with CharSequence, even more, some tools won't even notify you that there is potential bug in your code if you won't implement that method explicitly)
  • shmosel
    shmosel almost 7 years
    @Pavlus I think you're missing the fact that CharSequence overrides the contract to return exactly what anyone would expect.
  • Pavlus
    Pavlus almost 7 years
    @shmosel do I? What led you to such conclusion?
  • shmosel
    shmosel almost 7 years
    @Pavlus It sounds like you're trying to say the default toString() doesn't necessarily conform with what you'd expect from a CharSequence. If that's not it, I have no idea what you're saying.
  • Pavlus
    Pavlus almost 7 years
    @shmosel yes, it doesn't. Default contract is to represent object as String, CharSequence specifies how exactly do that (it still represents the object but in the specified way)
  • ChrisThomas
    ChrisThomas over 6 years
    This actually just bit me today. if charSequence is null then the returned string will be "null" and not null.
  • Abhishek Batra
    Abhishek Batra over 6 years
    Oh. Makes sense. I will remove this answer
  • Joust Knight
    Joust Knight almost 6 years
    By using the toString() method my CharSequence is displaying as, "[Ljava.lang.CharSequence;@26ae880a", not the text that was actually sent. toString() doesn't work.
  • Mike Samuel
    Mike Samuel almost 6 years
    @WillByers that output looks like the toString of a CharSequence array, not a CharSequence.
  • Shukant Pal
    Shukant Pal over 5 years
    I think this is perfect for some cases.
  • Hibbem
    Hibbem over 4 years
    Wanted to upvote, but can't change 333 to 334, sorry!
  • Padmanabha V
    Padmanabha V almost 4 years
    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(); }
  • Solubris
    Solubris over 3 years
    this actually causes the string to be copied twice, once in the sb.append(), and another time in the sb.toString()
  • horcrux
    horcrux over 3 years
    @Hibbem someone else did it for you ;-)
  • Kamafeather
    Kamafeather over 2 years
    The actual issue is that you can infer meaning just by having a string. There should be subtyping, when getting a String from a generic Object method: something like HashCodeString or ObjectSystemString or whatever. It's the return type from toString that is too generic, and exposes the side to ambiguity. Arguing on using a different object for generating the string, or on using a differently named method (that might still retain ambiguity) misses the point, IMHO.
  • Kamafeather
    Kamafeather over 2 years
    The expectation from toString on an Object and onto a CharSequence is to get returned a meaningful type. How the method is called is more for readability purposes; the name itself doesn't infer any guarantee about the context. What if I have a SyntheticMaterial with a toString method? What would string mean here? It might mean different things depending on the context (thexplorion.com/different-types-of-strings). Focusing on the name is misleading; we should focus on the return types, to discern the use case.
  • dropbear
    dropbear over 2 years
    @JamesFranken I'm having the same issue. I guess it's up to the implementer of the interface how this behaves. I solved it by using this instead: String.join("", myCharSequence)
  • Minhas Kamal
    Minhas Kamal over 2 years
    new StringBuilder(charSequence).toString(); will through NullPointerException if charSequence is null.