如何在android中比较字符串和字符数组?
我有一个字符串如何在android中比较字符串和字符数组?,android,string,character-arrays,Android,String,Character Arrays,我有一个字符串“sss”和一个字符数组{s','s','s'}。我将数组转换为字符串,但在比较它们时不会打印消息“两者相等”。为什么? public class RoughActivity extends Activity { private Button checkButton; private TextView text; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanc
“sss”
和一个字符数组{s','s','s'}
。我将数组转换为字符串,但在比较它们时不会打印消息“两者相等”。为什么?
public class RoughActivity extends Activity
{
private Button checkButton;
private TextView text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start();
}
private void start() {
int i;
checkButton=(Button)findViewById(R.id.go);
text=(TextView)findViewById(R.id.display);
final String question="sss";
final char answer[]=new char[question.length()];
for(i=0;i<question.length();i++)
{
answer[i]='s';
}
checkButton.setOnClickListener(new View.OnClickListener(){ //on clicking the button,the text must be filled with "both are equal"
public void onClick(View v){
if(question.equals(answer))
{
text.setText("both are equal");
}
}});
}
}
公共类活动扩展活动
{
私人按钮检查按钮;
私有文本查看文本;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start();
}
私有void start(){
int i;
checkButton=(按钮)findViewById(R.id.go);
text=(TextView)findViewById(R.id.display);
最后一个字符串question=“sss”;
最终字符答案[]=新字符[question.length()];
对于(i=0;i从char数组创建一个新字符串并进行比较)
If(question.equals(new String(answer)){
}
或
话虽如此,我无法想象为什么要尝试将答案存储在char[]中。从char数组创建一个新字符串并进行比较
If(question.equals(new String(answer)){
}
public boolean equals (Object object)
或
话虽如此,我无法想象您为什么试图将答案存储在char[]中
public boolean equals (Object object)
此方法将指定的对象与此字符串进行比较,如果它们相等,则返回true。该对象必须是具有相同顺序的相同字符的字符串实例
所以首先需要使用toString方法将其转换为first-to-String
例如:
String string = charArray.toString();
此方法将指定的对象与此字符串进行比较,如果它们相等,则返回true。该对象必须是具有相同顺序的相同字符的字符串实例
所以首先需要使用toString方法将其转换为first-to-String
例如:
String string = charArray.toString();
你可以使用一个循环
boolean equal = true;
for (int i = 0; i < answer.length; i++) {
if (!question.charAt(i) == answer[i] {
equal = false;
break;
}
}
boolean equal=true;
for(int i=0;i
我想这应该行。您可以使用循环
boolean equal = true;
for (int i = 0; i < answer.length; i++) {
if (!question.charAt(i) == answer[i] {
equal = false;
break;
}
}
boolean equal=true;
for(int i=0;i
我认为这应该行。您正在尝试将字符串与字符数组进行比较,这是两个非常不同的东西。您正在尝试将字符串与字符数组进行比较,这是两个非常不同的东西。。