0

I want to find a character within a string. If the character is found, add one to char_counter. How can I implement this?

Example:

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;
        }
    }
}
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41

3 Answers3

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;}
          }
    }
Rishi Dwivedi
  • 908
  • 5
  • 19
1

Your pseudo code:
password[i]

should be:

password.charAt(i)

Result:

if(password.charAt(i) == search.charAt(j)){ 
    char_counter = char_counter + 1;
}
Tyler
  • 17,669
  • 10
  • 51
  • 89
1

You can first convert you string into an array of characters using toCharArray() method like this:

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

And then use any of comparisons provided by java "equals". "Contains". Of course inside a for(string x: pass). Or a for loop with a counter++

z atef
  • 7,138
  • 3
  • 55
  • 50