如何在Java中搜索每个字符的字符串

时间:2014-02-25 04:23:29

标签: java string char string-search

我想在字符串中找到一个字符。如果找到该字符,请在char_counter中添加一个字符。我该如何实现呢?

示例:

int char_counter = 0;
String password = "1234";
String search = "1234";
for(int i = 0; i < password.length() - 1; i++) {
    for(int j = 0; j < search.length() - 1; j++) {
        //This is just pseudo code since I don't know how to properly search a string
        if(password[i] == search[j]) {
            char_counter = char_counter + 1;
        }
    }
}

4 个答案:

答案 0 :(得分:2)

I don't know what do you want to do if you want to compare your password and search
string character one bye than try this

     int char_counter = 0,i,j;
     String password = "1234";
     String search = "1234";
     if(password.length()==search.length()){    
        for(i=0,j=0;i<password.length();i++,j++){
            if(password.charAt(i)==search.charAt(j)){
                char_counter++;
            }
        }
    }


 if you want to search each character in password string than try this 

  for(int i = 0; i < password.length() - 1; i++){
     for(int j = 0; j < search.length() - 1; j++)
          {
              if(password.length() == search.length())
              { char_counter = char_counter + 1;}
          }
    }

答案 1 :(得分:1)

您的伪代码:
password[i]

应该是:

password.charAt(i)

结果:

if(password.charAt(i) == search.charAt(j)){ 
    char_counter = char_counter + 1;
}

答案 2 :(得分:1)

试试这个..

如果您这样做,您应该使用password[i] java将其作为数组

password.charAt(i)search.charAt(j)

您必须将条件用作 .equals

if(password.charAt(i).equals(search.charAt(i))){ 
    char_counter = char_counter + 1;
}

不是password[i] == search[j]

==总是只比较两个引用(对于非基元,即),即它测试两个操作数是否引用同一个对象。

但是,可以覆盖equals方法 - 因此两个不同的对象仍然可以相等...... Link

答案 3 :(得分:1)

您可以先使用toCharArray()方法将字符串转换为字符数组,如下所示:

Char[] pass = password.toCharArray();
Char[] sear = search.toCharArray();

然后使用java“equals”提供的任何比较。 “包含”。当然在for(字符串x:pass)中。或带有计数器++的for循环