Search code examples
javastringalgorithmintcharat

Java: is there an int method like charAt()?


I don't want "charAt(1);" to return the character at position 1 in the string... I want it to report all instances of "matching = 1;"

Take for example

int matching = 1;
int notMatching = 0;
int HI = matching;
int IH = notMatching; 
int searchString = theString.charAt(notMatching);

  int count = 0;
  int index = 0;

      while (0 < theString.length())
      {
      int  = theString.charAt(matching);
        if (theString.charAt(notMatching) == searchString)    
        {
        count = count + 1;
        }
        index = index + 1;
      }

Not a great example but basically what I want, or what this program is supposed to do is take a user input:

HIHIIH

and report the instances of HI spelled as IH... so the return would be for instance;

System.out.println("HI was spelled as IH" + count + "times");

EDIT: The "Duplicate" doesn't help me


Solution

  • You could use StringBuffer's reverse method and Pattern and Matcher as follows :

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class SearchReverseString {
        public static void main(String []args) {
            String str = "HIHIIH";
            String strToSearch = "HI";
            String strToSearchReversed = new StringBuffer(strToSearch).reverse().toString();
            Pattern strPattern = Pattern.compile(Pattern.quote(strToSearchReversed));
            Matcher matcher = strPattern.matcher(str);
            int counter = 0;
            while(matcher.find()) {
                ++counter;
            }
            System.out.println(strToSearch+" was spelt as "+strToSearchReversed+" "+counter+" times");
        }
    }
    

    The output is :

    HI was spelt as IH 2 times

    Note that in my program, str represents the input String and strToSearch represents the String to be searched in reverse order. The use of Pattern.quote ensures that any meta-characters are automatically escaped.