Posted By

DrPepper on 03/01/11


Tagged

charat


Versions (?)

[JAVA] CH13 check the char string


 / Published in: Java
 

charAt(#) find the char of #th therefore, you can compare char by char

  1. /*
  2.   Use recursion to implement a method boolean find(String t) that tests whether a string is contained in a sentence:
  3.   Sentence s = new Sentence("Mississippi");
  4.   boolean b = s.find("sip"); // return true
  5.   Hint: If the text starts with the string you want to match, then you are done. If not, consider the sentence that you obtain by removing the first character
  6.  
  7. http://snippets.dzone.com/posts/show/4908
  8. */
  9.  
  10. import java.util.Scanner;
  11. public class Sentence
  12. {
  13. public int max;
  14. public int maxNumBase;
  15. public int maxNumSub;
  16. public int i;
  17. public String base;
  18.  
  19. public Sentence(String word)
  20. { base = word; }
  21.  
  22. public boolean find(String str)
  23. {
  24. int m = 1;
  25. maxNumBase = base.length();
  26. max = maxNumBase - 1;
  27. for(i=1;i<max;i++)
  28. {
  29. if(base.charAt(i) == str.charAt(m))
  30. {
  31. m++;
  32. if(m == 3)
  33. { return true; }
  34. }
  35. else
  36. {
  37. if(m != 0)
  38. { i--; m--; }
  39. }
  40. }
  41. return false;
  42. }
  43. }
  44.  
  45. /**
  46.   Base.java
  47.   main here
  48. */
  49.  
  50. import java.util.Scanner;
  51.  
  52. public class Base
  53. {
  54. public static void main(String[] args)
  55. {
  56. Sentence s = new Sentence("Mississippi");
  57. boolean b = s.find("sip");
  58. System.out.println("*** Sentence.java ***");
  59. System.out.println("This is "+ b );
  60. }
  61. }

Report this snippet  

You need to login to post a comment.