How to convert CharSequence to String?
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
:
-
Type Casting:
String string = (String) charSequence;
-
Calling
toString()
:String string = charSequence.toString();
-
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());
}
}
Related videos on Youtube
![Belgi](https://i.stack.imgur.com/9QuUb.jpg?s=256&g=1)
Belgi
My name is Amir Belgi. I welcome you to visit my blog: https://thetightlycoupled.wordpress.com
Updated on January 25, 2022Comments
-
Belgi over 2 years
How can I convert a Java
CharSequence
to aString
?-
Minhas Kamal over 2 yearsSafest way:
String.valueOf(charSequence)
. Here is the detailed answer
-
-
Lodewijk about 11 yearsYou shouldn't make mistakes/make your code worse because others might have made a mistake.
-
Mike Samuel about 9 years@TheOnlyAnil, does calling
setText(CharSequence)
not do what you need? -
TheOnlyAnil about 9 yearsI want to make actionBar title clickable.
-
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 about 9 yearsStackoverflow won't let me post any question. :/ btw I did that last night. Custom actionbar is the solution :)
-
Gábor Lipták almost 9 yearsreturn new StringBuilder(charSequence).toString(); is a single liner equivalent.
-
earcam about 8 yearsTHIS ANSWER IS WRONG The
CharSequence
interface explicitly definestoString()
- 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 about 8 yearsIncidentially
StringBuilder
implementsCharSequence
, so you're now trusting the StringBuilder implementer did their job properly ツ -
fragorl about 8 yearsThe 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 almost 8 yearsThis 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 asList
orSet
, in particular theirequals()
andhashCode()
methods which will compile without overrides, but must be overridden according to the contract. -
fragorl almost 8 yearsSure, 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 almost 8 yearsThe 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 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 almost 7 years@Pavlus I think you're missing the fact that
CharSequence
overrides the contract to return exactly what anyone would expect. -
Pavlus almost 7 years@shmosel do I? What led you to such conclusion?
-
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 aCharSequence
. If that's not it, I have no idea what you're saying. -
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 over 6 yearsThis actually just bit me today. if
charSequence
is null then the returned string will be"null"
and notnull
. -
Abhishek Batra over 6 yearsOh. Makes sense. I will remove this answer
-
Joust Knight almost 6 yearsBy 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 almost 6 years@WillByers that output looks like the toString of a CharSequence array, not a CharSequence.
-
Shukant Pal over 5 yearsI think this is perfect for some cases.
-
Hibbem over 4 yearsWanted to upvote, but can't change 333 to 334, sorry!
-
Padmanabha V almost 4 yearsThis 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 over 3 yearsthis actually causes the string to be copied twice, once in the sb.append(), and another time in the sb.toString()
-
horcrux over 3 years@Hibbem someone else did it for you ;-)
-
Kamafeather over 2 yearsThe actual issue is that you can infer meaning just by having a string. There should be subtyping, when getting a
String
from a genericObject
method: something likeHashCodeString
orObjectSystemString
or whatever. It's the return type fromtoString
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 over 2 yearsThe expectation from
toString
on anObject
and onto aCharSequence
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 aSyntheticMaterial
with atoString
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 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 over 2 years
new StringBuilder(charSequence).toString();
will through NullPointerException ifcharSequence
isnull
.