I have a C program that displays all the substrings of a String:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char string[100];
void substrings(string str) {
if (strlen(str) >= 1) {
puts(str);
substrings(str + 1);
}
}
void todas_substrings(string str) {
int tam = strlen(str);
if (tam >= 1) {
substrings(str);
str[tam - 1] = 'UTFPR
TFPR
FPR
PR
R
UTFP
TFP
FP
P
UTF
TF
F
UT
T
U
';
todas_substrings(str);
}
}
int main(int argc, char const *argv[]) {
string str = "UTFPR";
todas_substrings(str);
return 0;
}
That results in:
public class Substring {
public void todasSubstrings(String str) {
int tamanho1 = 0;
int tamanho2 = str.length();
for(int i = 0; i < str.length(); i++) {
for(int j = 0; j < str.length(); j++) {
System.out.println(str.substring(tamanho1,tamanho2));
tamanho2--;
}
tamanho1++;
}
}
public static void main(String[] args) {
Substring sb = new Substring();
String str = "UTFPR";
sb.todasSubstrings(str);
}
}
However, the challenge now is to pass the same program to Java, but since Java already has a function for it, I did this:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 1, end 0, length 5
at java.base/java.lang.String.checkBoundsBeginEnd(Unknown Source)
at java.base/java.lang.String.substring(Unknown Source)
at Substring.todasSubstrings(Substring.java:10)
at Substring.main(Substring.java:22)
But it is giving the following error:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char string[100];
void substrings(string str) {
if (strlen(str) >= 1) {
puts(str);
substrings(str + 1);
}
}
void todas_substrings(string str) {
int tam = strlen(str);
if (tam >= 1) {
substrings(str);
str[tam - 1] = 'UTFPR
TFPR
FPR
PR
R
UTFP
TFP
FP
P
UTF
TF
F
UT
T
U
';
todas_substrings(str);
}
}
int main(int argc, char const *argv[]) {
string str = "UTFPR";
todas_substrings(str);
return 0;
}
What would be this error and how could you fix it to do the same function of the program in C?