Create a program checking that the string ens is a substring of obsensevity .

 boolean contains(String origin, String sub). 

Cannot use String.indexOf , String.contains . You need to convert the string to an array of characters and check.

Here is my task if someone can help I will be very grateful. If possible with splitting using split("") .

 public boolean contains(String origin, String sub) { String[] arrOrigin = origin.split(""); String[] arrSub = origin.split(""); int equals = 0; boolean result = false; if (arrOrigin.length >= arrSub.length) { for (int i = 0; i < arrSub.length; i++) { for (int j = 0; j < arrOrigin.length; j++) { if (arrOrigin[j].equals(arrSub[i])) { equals++; } } } if (equals == arrSub.length) { result = true; } } return result; } 
  • 2
    And just "obsensevity".contains("sen"); not? - Yuriy SPb
  • Unfortunately, String.contains is prohibited. This is still a learning task. It must be done as a teacher said. - Pavel
  • Related question: stackoverflow.com/questions/556097/… - Roman

4 answers 4

Here is another option using split :

 class MyTest { // Проверить, содержится ли pattern в examinee private static boolean contains(String examinee, String pattern) { if (pattern.length() > examinee.length()) return false; String s1 = " " + examinee + " "; // гарантируем непустую строку слева и справа String s2 = "\\Q" + pattern + "\\E"; // Трактовать как литерал if(s1.split(s2).length > 1) return true; // что-то есть и слева, и справа return false; }; // A Q&D test data set static String[][] testData = { {"qwerty", "wer"}, {"qwerty", "qwerty"}, {" qwerty", "qwerty"}, {"qwerty ", "qwerty"}, {"qwerty", " qwerty "}, {"по реке", "плывет"}, {"по реке", ".*"}, {"по реке", " "}, }; // Tests all the above data and shows the results public static void main(String[] args) { for (String[] pair: testData) System.out.printf("'%s' contains '%s': %s\n", pair[0], pair[1], contains(pair[0], pair[1])); } } 

Displays:

 'qwerty' contains 'wer': true
 'qwerty' contains 'qwerty': true
 'qwerty' contains 'qwerty': true
 'qwerty' contains 'qwerty': true
 'qwerty' contains 'qwerty': false
 'along the river' contains 'floats': false
 'along the river' contains '. *': false
 'along the river' contains '': true

  • Oh how interesting it means split can take arguments - Pavel
  • if (s1.split (s2) .length> 1) return true And what happens in the split method if you send a string there? - Pavel
  • @Pavel, split accepts a string as an argument, which it interprets as a regular expression, and splits the source string into substrings in those places where this regular expression matches: "cuck", "river", "hand"}. See docs.oracle.com/javase/8/docs/api/java/lang/… - m. vokhm
  • And yes, I realized a cool thing and a short decision that is always pleasant. Only it will not work if the substring is at the end or at the beginning of the original string. The resulting array will also have length = 1. - Pavel
  • @Pavel, how it will not work - here are the lines in the test data: {" qwerty", "qwerty"}, {"qwerty ", "qwerty"} , and the output to the console is shown. Copy the entire program to yourself, substitute any test data and run, check. - m. vokhm

The program might look like this.

 import java.util.*; import java.lang.*; import java.io.*; class Ideone { static boolean contains(String origin, String sub) { String[] originArray = origin.split( "" ); String[] subArray = sub.split( "" ); int originLength = originArray.length; int subLength = subArray.length; boolean found = false; if ( subLength <= originLength ) { for ( int i = 0; !found && i < originLength - subLength + 1; i++ ) { int j = 0; while ( j < subLength && originArray[i + j].equals( subArray[j] ) ) j++; found = j == subLength; } } return found; } public static void main (String[] args) throws java.lang.Exception { String origin = "obsensevity"; String sub = "ens"; System.out.println( "\"" + origin + "\" contains \"" + sub + "\" is " + contains( origin, sub ) ); } } 

Its output to the console

 "obsensevity" contains "ens" is true 
  • Could you explain this place here, sorry if it's a stupid question. - Pavel
  • while (j <subLength && originArray [i + j] .equals (subArray [j])) j ++; found = j == subLength; - Pavel
  • Especially originArray [i + j] .equals (subArray [j] - Pavel
  • and here it is found = j == subLength - Pavel
  • four
    I need to understand and decide for myself. Meaning to take the job done not by me if I can not repeat it myself? Inflammation of the trick would be good if the cash flow went in the opposite direction. And so get a ticket and go on foot. - Pavel

That made the decision myself, based on your tips. Thank you all very much! Especially Vlad for Moscow for patience.

  public boolean contain(String origin, String sub) { if (origin.length() < sub.length()) { return false; } char[] arrOrigin = origin.toCharArray(); char[] arrSub = sub.toCharArray(); for (int i = 0; i <= arrOrigin.length - arrSub.length; i++) { if (arrSub[0] == arrOrigin[i]) { char[] forEqual = new char[arrSub.length]; System.arraycopy(arrOrigin, i, forEqual, 0,arrSub.length); if (Arrays.equals(forEqual, arrSub)) { return true; } } } return false; } 
  • It remains to write a pack of unit tests with cases involving different registers, unicode, etc. ) - Nick Volynkin
  • This will work, but if I were you, I would look again at the decisions of the other participants (for example, Vlad), you are constantly re-allocating memory and copying, which is not very good in terms of performance. - pavel
  • pavel is right. And also if (arrOrigin.length < arrSub.length) { return false; } if (arrOrigin.length < arrSub.length) { return false; } it is better to put at the very beginning - if the sample length exceeds the length of the source string, then there is no need to build arrOrigin, arrSub character arrays - it will be a waste of processor time. And the result variable does not change anywhere - it’s better not to describe it, and at the end to use a constant: return false - the code will be simpler and clearer - m. vokhm
  • Unit tests I did just did not lay out did not want to clutter the space. Yes, about the fact that pavel said this yes, really 100% right, I'll think about it and try to correct it. Thank you for your comment. - Pavel
  • one
    Vlad has the best solution, as far as performance is concerned! But, I still can’t get into these cycles (((. Probably, I didn’t overheat much, I need to get distracted and then see what he is doing there again. He tried to explain to me, but I’m pursuing clever thoughts, but I'm faster. ..))) - Pavel

Oh, I did not notice at the beginning that you need to use character arrays. Then like this:

  static private boolean contains2 (String examinee, String pattern) {
     if (pattern.length ()> examinee.length ()) return false; 
     char [] origAry = examinee.toCharArray ();
     char [] ptrnAry = pattern.toCharArray ();
     for (int i = 0; i <= (origAry.length - ptrnAry.length); i ++) {
       for (int j = 0; j <ptrnAry.length; j ++) {
         if (origAry [i + j]! = ptrnAry [j]) break;
         if (j == ptrnAry.length - 1) return true;
       }
     }
     return false;
   };
But how to splash the split here, I can't think of it.