[英]Compares two strings lexicographically using charAt() and without using compareTo() method
如果第一個字符串在字典上大於第二個字符串,則應返回1,如果等於,則返回0,否則為-1。在某些情況下,它正確返回為1,-1,0,但是對於此str1和str2,返回結果為與所需輸出相反。
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]) {
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1, testcase2);
System.out.println("Result : " + result);
}
// write your code here
public int newCompare(String str1, String str2) {
int l1 = str1.length();
int l2 = str2.length();
int max = 0;
if (l1 <= l2) {
max = l1;
}
else
max = l2;
int count = 0;
for (int i = 0; i < max; i++) {
char ch1 = str1.charAt(i);
char ch2 = str2.charAt(i);
if (str2.charAt(i) > str1.charAt(i)) {
return - 1;
}
if (str1.charAt(i) > str2.charAt(i)) {
return 1;
}
if (l1 == l2) {
if (ch1 == ch2) {
count++;
}
if (count == max) {
return 0;
}
}
}
if (l1 == l2) return 0;
if (l1 > l2)
return 1;
else
return - 1;
}
}
這是一個簡化的答案
public class TestStrings {
public static void main(String[] args) {
System.out.println(compare("Mike", "Mike")); // returns 0
System.out.println(compare("Mikee", "Mike")); // returns 1
System.out.println(compare("Mike", "Mikee")); // returns -1
}
public static int compare(String s1, String s2) {
for (int i = 0; i < Math.min(s1.length(), s2.length()); i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 > c2) {
return 1;
} else if (c2 > c1) {
return -1;
}
}
if (s2.length() > s1.length()) {
return -1;
} else if (s1.length() > s2.length()){
return 1;
} else {
return 0;
}
}
}
我使用了一個循環,以停止條件為最短單詞的長度。 如果在最短單詞的長度之后單詞相等,則較長的單詞會自動變大。 這就是底部的if語句的作用。
你可以試試:
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]){
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1,testcase2);
System.out.println("Result : "+result);
}
//write your code here
public int newCompare(String str1, String str2){
int l1=str1.length();
int l2=str2.length();
int max=0;
if(l1<=l2)
{
max =l1;
}
else
max=l2;
int count=0;
for (int i =0;i<max;i++) {
char ch1=str1.charAt(i);
char ch2=str2.charAt(i);
if(str2.charAt(i)>str1.charAt(i))
{
return -1;
}
if(str1.charAt(i)>str2.charAt(i))
{
return 1;
}
}
if(l1==l2)
{
return 0;
}else if (l1 < l2){
return -1;
}else{
return 1;
}
}
在這種情況下,其中字符串testcase1 =“HelloWorld”的和字符串testcase2 =“hellojavaworld”您的for循環將從字符“H”運行到char的if條件的內部為 “O”(i = 0到i = 4的)和無循環將得到滿足,一旦我增加到5
//str1.charAt(i)='w' and str2.charAt(i)=j
if(str1.charAt(i)>str2.charAt(i)) //w(ASCII=119) > j(ASCII=106)
{
return 1; //return 1 and control return to the calling function
}
所以result = 1 。 簡而言之,您的代碼可以正常工作。 您可以指定要輸出的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.