Steven Villarreal
Steven Villarreal

Reputation: 39

How to return the 3 middle characters of an odd string using the substring method?

I'm trying to return the middle 3 characters of a word using the substring method but how do I return the middle 3 letters of a word if the word can be any size (ODD only)?

My code looks like this.

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
     Scanner scnr = new Scanner(System.in);
     String inputWord;

     inputWord = scnr.next();

     System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring(2,5));

  }
}

The reason I have a 2 and 5 in the substring method is because I have tried it with the word "puzzled" and it returned the middle three letters as it was supposed to do. But if I try, for instance "xxxtoyxxx", It prints out "xto" instead of "toy".

P.S. Please don't bash me I'm new to coding :)

Upvotes: 0

Views: 4219

Answers (4)

Reece Nunez
Reece Nunez

Reputation: 1

In order to find the middle three of an odd character string, you must first find the middle index. To do this you would write something like this:

import java.util.Scanner;
public class LabProgram {
   public static void main(String[] args) {

        Scanner scnr = new Scanner(System.in);
        
        String input = scnr.nextLine();
        int length = input.length();
        
        int middleIndex = length / 2;

Now that you have the middle index the start of the first three should be middleIndex - 1 and the end of the middle three should be middleIndex + 2. Use substring to find the middle three.

String middleThree = input.substring(middleIndex -1, middleIndex + 2);
    
System.out.println("Midfix: " + middleThree);

Upvotes: 0

Zephyr
Zephyr

Reputation: 10253

Consider the following code:

String str = originalString.substring(startingPoint, startingPoint + length)

To determine the startingPoint, we need to find the middle of the String and go back half the number of characters as the length we want to retrieve (in your case 3):

int startingPoint = (str.length() / 2) - (length / 2);

You could even build a helper method for this:

private String getMiddleString(String str, int length) {
    if (str.length() <= length) {
        return str;
    }

    final int startingPoint = (str.length() / 2) - (length / 2);
    return "[" + str.substring(startingPoint, startingPoint + length) + "]";
}

Complete Example:

class Sample {
    public static void main(String[] args) {
        String text = "car";

        System.out.println(getMiddleString(text, 3));
    }

    private static String getMiddleString(String str, int length) {

        // Just return the entire string if the length is greater than or equal to the size of the String
        if (str.length() <= length) {
            return str;
        }

        // Determine the starting point of the text. We need first find the midpoint of the String and then go back
        // x spaces (which is half of the length we want to get.
        final int startingPoint = (str.length() / 2) - (length / 2);
        return "[" + str.substring(startingPoint, startingPoint + length) + "]";

    }
}

Here, I've put the output in [] brackets to reflect any spaces that may exist. The output of the above example is: [ppl]

Using this dynamic approach will allow you to run the same method on any length of String. For example, if our text String is "This is a much longer String..." our output would be: [ lo]


Considerations:

  • What if the input text has an even number of characters, but the length is odd? You would need to determine if you want to round the length up/down or return a slightly off-center set of characters.

Upvotes: 1

Joe
Joe

Reputation: 1342

This will get the middle of the string, and return the characters at the middle, and +- 1 from the middle index.

public static String getMiddleThree(String str) {
    int position, length;
    if (str.length() % 2 == 0) {
        position = str.length() / 2 - 1;
        length = 2;
    } else {
        position = str.length() / 2;
        length = 1;
    }
    int start = position >= 1 ? position - 1 : position;
    return str.substring(start, position + 1);
}

The work left you have to do is make sure the end position is not greater than the length of the string, otherwise, choose the position as the final index

Upvotes: 0

Victor Luna
Victor Luna

Reputation: 1814

I think what you can do is to calculate the string length then divided by 2. This gives you the string in the middle, then you can subtract one to the start and add 2 to the end. If you want to get the first two for an odd string, then subtract 2 to the start index and add 1 to the end.

String word_length = inputWord.length()/2;
System.out.println("Enter word: " + inputWord + " Midfix: " + inputWord.substring((word_length-1, word_length+2));

Hope this helps.

Upvotes: 0

Related Questions