I am learning Java, so I am beginner. I know I can do this with split function but I want to improve my algorithm knowledge.
I will be glad if you help me. Thanks.
- inputStr variable is contains the string entered by the user.
- stopPos variable is contains the order of wanted the word.
- parseWith variable is contains which char to parse the string.
public static String parseStr(String inputStr, int stopPos, char parseWith) {
String toReturn = "";
int unitCount = 0;
for(int Iterator = 0; Iterator < inputStr.length(); Iterator = Iterator + 1){
if (inputStr.charAt(Iterator) == parseWith){
if (unitCount == stopPos) break;
toReturn = "";
continue;
}
if (toReturn == "") unitCount = unitCount + 1;
toReturn += inputStr.charAt(Iterator);
}
try{
return toReturn;
} catch(Exception e){
return null;
}
}
Here's an example of using:
public static void main(String[] args) {
Scanner userEntry = new Scanner(System.in);
System.out.print("Enter two numbers separated by space: ");
String inputStr = userEntry.nextLine();
int frstPart = Integer.parseInt(parseStr(inputStr, 1, ' '));
int scndPart = Integer.parseInt(parseStr(inputStr, 2, ' '));
}
EDIT
I have changed some things from first part of code in here.
try{
return toReturn;
} catch(Exception e){
return null;
}
to
toReturn = (unitsCounter == stopPos) ? toReturn : null;
return toReturn;