I'm just looking for a simple way to be able to extract substrings without using the substring method.
Asked
Active
Viewed 9,426 times
-2
-
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 Answers
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
- Take your original string and get a character array (
char[] myChars = myString.toCharArray();
, for example) - Copy the character array into a new, shorter one (
char[] mySubstringChars = ...
) - 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:
- You do not need to
String.valueOf
to convert thechar
value toString
value before appending it to the string because StringBuilder supports appending achar
value to it directly. You can avoid the creation of a lot of
String
objects because sinceString
is an immutable class, every attempt to change the string will create a newString
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