在Android中编程,大多数文本值都在预期中CharSequence
.
这是为什么?有什么好处,使用CharSequence
过的主要影响是String
什么?
在使用它们和从一个转换到另一个时,主要的区别是什么,预期会出现什么问题?
如何将Java转换CharSequence
为String
?
我读过上一篇文章.任何人都可以说CharSequence
和String 之间的确切区别是什么,除了String
实现的事实CharSequence
和那String
是一个字符序列?例如:
CharSequence obj = "hello";
String str = "hello";
System.out.println("output is : " + obj + " " + str);
Run Code Online (Sandbox Code Playgroud)
当"hello"分配给obj
和再次分配时会发生什么str
?
最简单的方法CharSequence[]
是ArrayList<String>
什么?
当然,我可以遍历每个ArrayList
项目并复制到CharSequence
数组,但也许有更好/更快的方式?
我将一个spannable对象分成3个部分,做不同的操作,然后我需要合并它们.
Spannable str = editText.getText();
Spannable selectionSpannable = new SpannableStringBuilder(str, selectionStart, selectionEnd);
Spannable endOfModifiedSpannable = new SpannableStringBuilder(str, selectionEnd, editText.getText().length());
Spannable beginningOfModifiedSpannable = new SpannableStringBuilder(str, 0, selectionStart);
Run Code Online (Sandbox Code Playgroud)
我该怎么做?我还没有找到所需的方法或构造函数.
我最近注意到,当涉及转义字符"\"(斜杠)时,String.replaceAll(正则表达式,替换)表现得非常奇怪.
例如,考虑有一个与文件路径字符串- String text = "E:\\dummypath"
我们要替换的"\\"
用"/"
.
text.replace("\\","/")
给出输出"E:/dummypath"
,然后text.replaceAll("\\","/")
引发异常java.util.regex.PatternSyntaxException
.
如果我们想要实现相同的功能,replaceAll()
我们需要将其编写为,
text.replaceAll("\\\\","/")
一个值得注意的区别是replaceAll()
它的参数是reg-ex而replace()
有参数字符序列!
但text.replaceAll("\n","/")
其作用与其char序列完全相同text.replace("\n","/")
深入挖掘: 当我们尝试其他一些输入时,可以观察到更奇怪的行为.
让我们分配 text="Hello\nWorld\n"
现在
text.replaceAll("\n","/")
,text.replaceAll("\\n","/")
,text.replaceAll("\\\n","/")
这三个提供同样的输出Hello/World/
Java以我认为最好的方式搞砸了reg-ex!没有其他语言似乎在reg-ex中具有这些有趣的行为.任何特定的原因,为什么Java搞砸了这样?
将单个char传递给期望CharSequence的方法的最有效方法是什么?
这就是我所拥有的:
textView.setText(new String(new char[] {c} ));
Run Code Online (Sandbox Code Playgroud)
根据这里给出的答案,这是一种明智的方式,在输入是字符数组的情况下.我想知道是否有一个偷偷摸摸的快捷方式,我可以应用于单一案例中.
是否可以通用参数化接受EAEER ClassA或InterfaceB的方法?
由于|不编译 伪代码
public <T extends Number | CharSequence> void orDoer(T someData){ // ... }
Run Code Online (Sandbox Code Playgroud)
即不是写多个方法签名,我希望这个方法接受Number或CharSequence作为参数
应该使用Number或CharSequence参数传递
orDoer(new Integer(6));
int somePrimitive = 4;
orDoer(somePrimitive);
orDoer("a string of chars");
Run Code Online (Sandbox Code Playgroud) 有没有办法将Charsequence或String转换为Ingeter?
CharSequence cs = "123";
int number = (int) cs;
Run Code Online (Sandbox Code Playgroud)
我是Noob.解:
CharSequence cs = "123";
int number = Integer.parseInt(cs);
Run Code Online (Sandbox Code Playgroud)