Android字符串不等于

时间:2011-05-24 14:19:53

标签: android string equals

我是Java和Android的新手,所以我相信这将是一个简单的问题/答案。我知道要找出一个字符串是否等于另一个字符串,你使用相等的函数。在我的情况下,我正在扫描一个QR码,其扫描结果类似于“EMPLOYEE ~~ John Smith ~~ DIVISION ~~ Maintenance”。我需要知道如何执行以下操作:

String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"

String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?

String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"

if (myJunk[0].equals(val1)){
    // Do Something
}

在示例Java代码中,myJunk [0]永远不等于val1。我做错了什么?

3 个答案:

答案 0 :(得分:2)

我试过这个并且它有效,所以尝试显示内容变量,可能问题出在附加内容中,尝试在logCat中显示它:

String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
 String[] myJunk = contents.split("~~");
 // This should split everything up into an array named myJunk (right)?

 String val1 = myJunk[0];
 Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
 Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
 // Now val1 Should be equal to "EMPLOYEE"

 if (myJunk[0].equals(val1)){
     Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
 }

答案 1 :(得分:0)

你的字符串是: EMPLOYEE~~John Smith~~DIVISION~~Maintenance

分裂后,我的Junk [0]将包含EMPLOYEE(注意EMPLOYEE这个词前面的空格)。

因此,在比较之前,您需要trim您的价值

答案 2 :(得分:0)

我经常使用的方法是在有疑问时打印出我的变量。所以如果你不确定问题出在哪里,你可以试试这样的事情。 (它要求您能够在logcat中查看输出)

String contents = intent.getStringExtra("SCAN_RESULT"); 
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );

String[] myJunk = contents.split("~~"); 
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);

String val1 = myJunk[0]; 
// Now val1 Should be equal to "EMPLOYEE"

for(int i=0; i < myJunk.length; i++) {
  System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.

if (myJunk[0].equals(val1)){     
// Do Something 
} 

这有点矫枉过正,但这主要是为了显示获取查找问题所需的所有信息的一种方法:)