Jump to content

Need help figuring out strings in java

Cookiecrumbles222

hay guys can anyone help me figure out how to do this I'm very stumped, I'm also pretty new to java so i don't know many keywords. if anyone could help me figure this out it would be much appreciated. (its java code)(its 11-3) thanks for any help.

image (1).jpeg

Link to comment
Share on other sites

Link to post
Share on other sites

Are you stumped on the entire question?

 

If it's just checking to see if one string contains another then it could be something like this:

mainText.toLowerCase().contains(targetWord.toLowerCase())

This would return a boolean to indicate if the text in the file contains the entered target word (true if it's there and false if not), mainText would be a String containing the text from the file and targetWord would be a String from the input.

 

If you want the position in the string where the target word starts you could use something like this:

mainText.toLowerCase().indexOf(targetWord)

This would return the first point in the string the target word is found. You could then split the string up using substring and do the search again to find the next point.

 

You can then get every occurrence of a word with a loop. Sort of something like this:

String mainText = "Hello World. World. This is a test string. Hello World. Hello"; // Text you will go get from file.
String targetWord = "world"; // Target word to get from input

if (mainText.toLowerCase().contains(targetWord.toLowerCase()))
{
  // Target word is there
  for (int i = 0; i < mainText.length(); i++)
  {
    // Get the first index of the matching word
    int position = mainText.toLowerCase().indexOf(targetWord, i);

    if (position >= 0)
    {
      // Word found 
      System.out.println("Target word found at position " + position);
      i = position; // Increase the loop index to the start of the word
    }
    else 
    {
      // No more words found so exit out of loop
      break;
    }
  }
}
else
{
  System.out.println("Target word not found");
}

 

I used System.out.println but you would return that whatever way you want.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×