Can somebody please show me a bit of code to convert a string to charsequence?
Asked
Active
Viewed 4.4k times
3 Answers
30
String implements the Interface CharSequence, so String is a CharSequence.
And you may never instantiate interfaces. Wherever CharSequence is required, String will fit.

MByD
- 135,866
- 28
- 264
- 277
-
so a straightforward cast will work? ie Charsequence cs = (Charsequence) String str; – Apr 28 '11 at 11:15
-
2No cast is needed, and you can't cast anyway. String is a CharSequence. – MByD Apr 28 '11 at 11:18
-
This (for example) is a valid assignment: `CharSequence cs = new String("hello");` – MByD Apr 28 '11 at 11:20
-
Let me get this right - I can use string and charsequence interchangeably with no modifications, casting or whatever? Like, String str="abc"; Charsequence cs; cs = str; and vice versa? – Apr 28 '11 at 11:24
-
1No. the first side is true, but its inheritance, which is one-way. "Every Drug Dealer is a criminal, but not every criminal is a drug dealer" :) more seriously, read the java tutorial about interfaces, it worth reading: http://download.oracle.com/javase/tutorial/java/IandI/createinterface.html – MByD Apr 28 '11 at 11:30
-
The actual bit of code I am using right now is EditText, which requires a charsequence. If I use a string... editBox.setText(str); that's OK? – Apr 28 '11 at 11:34
-
Note that CharSequence cs = new String("hello"); is *not* necessary - one only needs CharSequence cs = "hello"; You should avoid calling the String(String) constructor in almost all cases - it wastes resources and is very rarely needed (only if you really want two different instances) – djb Sep 09 '11 at 17:59
2
Try this:
// final CharSequence cs = mEditText.getText();
final CharSequence cs = "Hi how are u";
String[] vals = cs.toString().split(" ");
for(int i=0;i<vals.length;i++) {
System.out.println("args values...."+i+""+vals[i].toString());
}

kiheru
- 6,588
- 25
- 31
2
As MByD pointed, String
implements CharSequence
, so its already a CharSequence
. But if you want to convert CharSequence
to String
, Here is the code:
CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"
public void foo(CharSequence cs) {
System.out.println(cs);
}
The SO thread can be found here

Community
- 1
- 1

Adil Soomro
- 37,609
- 9
- 103
- 153
-
1
-
But "string" is a String. and that thread was asked the same as you asked. A simple google by copying your title gave me [Thread](http://www.google.com.pk/search?q=string+to+charsequence%3F&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a#sclient=psy&hl=en&client=firefox-a&hs=8D5&rls=org.mozilla:en-US%3Aofficial&source=hp&q=string+to+charsequence&aq=f&aqi=&aql=&oq=&pbx=1&fp=dfdcd119b0bef06c&biw=1280&bih=558) – Adil Soomro Apr 28 '11 at 11:26