Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over a string in Java?

Tags:

java

string

public static Boolean cmprStr( String s1, String s2 )
{
    // STUFF
}

I want to iterate through s1 to make sure that every character in s1 is included in s2.

like image 901
Shamoon Avatar asked May 30 '11 16:05

Shamoon


People also ask

Can a for loop iterate over a string?

The for loop is used to iterate over structures like lists, strings, etc. Strings are inherently iterable, which means that iteration over a string gives each character as output.

How do you read all characters in a string in Java?

To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character.


6 Answers

public static Boolean cmprStr( String s1, String s2 )
{
    for (int i = s1.length() - 1; i >= 0; --i) {
         if (s2.indexOf(s1.charAt(i)) == -1) {
             return Boolean.FALSE;
         }
    }
    return Boolean.TRUE;
}
like image 169
Ted Hopp Avatar answered Sep 28 '22 18:09

Ted Hopp


  for(char c: s1.toCharArray()){
     if(s2.indexOf(c) == -1){
           return false;
     }
  }
  return true;

Assuming that

  s1 = "aabb";
  s2 = "ccddaannbbss";

will return true.

like image 26
Vincent Ramdhanie Avatar answered Sep 28 '22 19:09

Vincent Ramdhanie


length()

will give you the length of a string

charAt( someIndex)

will give you the character at a given position, so you can iterate the first String.

indexOf( achar )

will give you the poisition a char in a String, or -1 if it's not there. hence you should be able to look for each character in the first string within the second.

like image 24
djna Avatar answered Sep 28 '22 18:09

djna


All the other answers are O(n^2). Here's a way that is linear in time (i.e. O(n)) using Google Guava:

  public static boolean cmprStr(String s1, String s2) {
    Set<Character> desiredCharacters = Sets.newHashSet(Lists.charactersOf(s2));
    return Sets.difference(Sets.newHashSet(Lists.charactersOf(s1)), desiredCharacters).isEmpty();
  }
like image 42
sjr Avatar answered Sep 28 '22 17:09

sjr


Set<Character> charsInS1 = new HashSet<Character>();
for (int i = 0; i < s1.length(); i++) {
  charsInS1.add(s1.charAt(i));
}
for (int i = 0; i < s2.length(); i++) {
  charsInS1.remove(s2.charAt(i));
}
return charsInS1.isEmpty();

This has a complexity of O(n+m)... answers using indexOf have an O(n*m) complexity. It does of course use a bit of extra memory temporarily though.

like image 37
ColinD Avatar answered Sep 28 '22 19:09

ColinD


Why don't you simply use 'equals' method ?

Boolean b = s1.equals(s2);
like image 31
jlink Avatar answered Sep 28 '22 17:09

jlink