-2

I'm just looking for a simple way to be able to extract substrings without using the substring method.

  • treat the string like an array using `charAt` and extract it yourself. – toastedDeli Oct 19 '19 at 20:21
  • You can always look into the source code of the substring method. – Harshal Parekh Oct 19 '19 at 20:27
  • Can you add a code where you intend to extract the data or text without having to use substring() method. Of course there many ways you can implement your code but add what you have done or your approach here. – Juniar Oct 20 '19 at 03:08

2 Answers2

0

I'm assuming this is a homework question, but if you want a hint you can use myString.toCharArray() to extract a char[] of every character in the string and myString.charAt(0) to get a character at index 0 for example.

You can also construct a new String from a character array new String(myCharArray) thus you can trivially just

  1. Take your original string and get a character array (char[] myChars = myString.toCharArray();, for example)
  2. Copy the character array into a new, shorter one (char[] mySubstringChars = ...)
  3. Change the shorter char array back into a String (String mySubstring = new String(mySubstringChars);)
Rubydesic
  • 3,386
  • 12
  • 27
  • Thanks for the answer. It is a homework question, but we haven't learnt arrays, functions or other fancy stuff. We're as far as variable declaration and using simple string methods. I'm pretty sure you could make a function that does the job of the substring method, but as I said, I'm a complete beginner. – DoktoriPartise19 Oct 19 '19 at 20:33
0

You can do it as follows:

public class Test {
    public static void main(String args[]) {
        String str = "Hello World!";
        String newStr = "";
        int startFrom = 2, endBefore = 5;// test startFrom and endBefore indices
        for (int i = startFrom; i < endBefore; i++)
            newStr += String.valueOf(str.charAt(i));
        System.out.println(newStr);
    }
}

Output:

llo

[Update]

Using StringBuilder has two obvious advantages:

  1. You do not need to String.valueOf to convert the char value to String value before appending it to the string because StringBuilder supports appending a char value to it directly.
  2. You can avoid the creation of a lot of String objects because since String is an immutable class, every attempt to change the string will create a new String object. You check a good discussion here.

    public class Test {
        public static void main(String args[]) {
            String str = "Hello World!";
            StringBuilder newStr = new StringBuilder();
            int startFrom = 2, endBefore = 5;// test startFrom and endBefore indices
            for (int i = startFrom; i < endBefore; i++)
                newStr.append(str.charAt(i));
            System.out.println(newStr);
        }
    }
    
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110