Word in java string

I am very new to Java and as a starter I was suggested to try this at home.

Write a program that specifies the number of occurrences of a smaller line in a larger line as part of it, as well as a single word. For example,

Large line = "I AM IN AMSTERDAM", smaller line = "AM".

Output: as part of string: 3, as part of word: 1.

While I was doing the nail of the second part (as part of a word) and even had my transition on the first (searching for a word as part of a string), I just don't understand how to crack the first part. It keeps showing 1 for me with an example input where it should be 3.

I definitely made a mistake - I would be very grateful if you can point out the error and correct it. As a request, I am a curious student, so if it is possible (at your will) please provide an explanation why this is so.

import java.util.Scanner;
public class Program {
static Scanner sc = new Scanner(System.in);
static String search,searchstring;
static int n;
void input(){
    System.out.println("What do you want to do?"); System.out.println("1.     
Search as part of string?");
    System.out.println("2. Search as part of word?");
    int n = sc.nextInt();
    System.out.println("Enter the main string"); searchstring = 
sc.nextLine();
    sc.nextLine(); //Clear buffer
    System.out.println("Enter the search string"); search = sc.nextLine();
}
static int asPartOfWord(String main,String search){
    int count = 0; 
    char c; String w = "";
    for (int i = 0; i<main.length();i++){
        c = main.charAt(i);
        if (!(c==' ')){
            w += c;
        }
        else {
            if (w.equals(search)){
                count++;
            }
            w = ""; // Flush old value of w
        }
    }
    return count;
}
static int asPartOfString(String main,String search){
    int count = 0;
    char c; String w = ""; //Stores the word 
    for (int i = 0; i<main.length();i++){
        c = main.charAt(i);
        if (!(c==' ')){
            w += c;
        }
        else {
            if (w.length()==search.length()){
                if (w.equals(search)){
                    count++;
                }
            }
            w = ""; // Replace with new value, no string
        }
    }
    return count;
}
public static void main(String[] args){
    Program a = new Program();
    a.input();
    switch(n){
        case 1: System.out.println("Total occurences: " + 
         asPartOfString(searchstring,search));
        case 2: System.out.println("Total occurences: " +  
         asPartOfWord(searchstring,search));
        default: System.out.println("ERROR: No valid number entered");
    }
  }
}

      

EDIT: I will be using a loop structure.

+3


source to share


5 answers


The simplest way would be to use regexes (this will probably defeat the idea of ​​writing it yourself, although learning regexes is a good idea because they are so powerful: since you can see that the core of my code is 4 lines long per method countMatches

).

public static void main(String... args) {
  String bigger = "I AM IN AMSTERDAM";
  String smaller = "AM";

  System.out.println("Output: As part of string: " + countMatches(bigger, smaller) +
          ", as a part of word: " + countMatches(bigger, "\\b" + smaller + "\\b"));
}

private static int countMatches(String in, String regex) {
  Matcher m = Pattern.compile(regex).matcher(in);
  int count = 0;
  while (m.find()) count++;
  return count;
}

      

How it works?



  • we create Matcher

    that finds a specific pattern in your string and then iterate to find the next match until there are none left and increment the counter
  • patterns themselves: "AM"

    matches any occurrence AM

    in a string at any position. " \\bAM\\b

    " will only match whole words ( \\b

    is a word separator).

This may not be what you were looking for, but I thought it would be interesting to see a different approach. Technically I'm using a loop :-)

+3


source


While writing your own code with a lot of loops to work can lead to a faster (debatable) one, it is better to use the JDK if possible because there is less code to write, less debugging, and you can focus on high performance rather than low-level iteration and comparison implementations. characters.

So, the tools you need to do this already exist, and while using them requires knowledge that you don't have, they are elegant to be one line of code for each method.

Here's how I would solve:

static int asPartOfString(String main,String search){
    return main.split(search, -1).length - 1;
}

static int asPartOfWord(String main,String search){
    return main.split("\\b" + search + "\\b", -1).length - 1
}

      



See a live demo of this code, running with your example input, which (perhaps intentionally) contains an edge-to-edge (see below).

Performance? Probably a few microseconds is fast enough. But the real benefit is so little code that it completely cleans up what is happening and almost nothing happens, or that debugging is required.

What you need to know to use this solution:

  • regex term for "word boundary" - \b

  • split()

    takes a regex as its search term
  • The 2nd parameter split()

    controls the behavior at the end of the line: a negative number means "keep whitespace at the end of the split", which process the edge of the main line ending with a smaller line. No -1

    split call will throw out the workpiece in this case.
+1


source


You can use regular expressions, try ".*<target string>.*"

(Replace target string

with what you are looking for.

Look at the Java Doc for "Patterns and Regular Expressions"

To search for occurrences in a string, this can be helpful.

Matcher matcher = Pattern.compile(".*AM.*").matcher("I AM IN AMSTERDAM")
int count = 0;

while (matcher.find()) {
    count++;
}

      

0


source


For the first part of your exercise, this should work:

static int asPartOfWord(String main, String search) {
    int count = 0;
    while(main.length() >= search.length()) { // while String main is at least as long as String search
         if (main.substring(0,search.length()).equals(search)) {  // if String main from index 0 until exclusively search.length() equals the String search, count is incremented;
             count++;
         }
    main = main.substring(1); // String main is shortened by cutting off the first character
    }
    return count;

      

You might think about how you name your variables:

   static String search,searchstring;
   static int n;

      

While search and searchstring will tell us what they mean, you must write the first word in lowercase, each subsequent word must be written with the first letter in uppercase. This improves readability.

static int n won't give you much information on what it is used for, if you read your code again after a few days, you can use something more descriptive here.

  static String search, searchString;
  static int command;

      

0


source


Here's an alternative (and much shorter) way to make it work with Pattern and Matcher , or better known as regex.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountOccurances {

    public static void main(String[] args) {

        String main = "I AM IN AMSTERDAM";
        String search = "AM";

        System.out.printf("As part of string: %d%n",
                asPartOfString(main, search));

        System.out.printf("As part of word: %d%n",
                asPartOfWord(main, search));        
    }

    private static int asPartOfString(String main, String search) {

        Matcher m = Pattern.compile(search).matcher(main);
        int count = 0;
        while (m.find()) {
            count++;
        }
        return count;
    }

    private static int asPartOfWord(String main, String search) {

        // \b - A word boundary
        return asPartOfString(main, "\\b" + search + "\\b");
    }
}

      

Output:

As part of string: 3
As part of word: 1

      

0


source







All Articles