-1

If there is a given
Inputs
String "abcdaa/efgh/hidjk/lmno/pqrs/tuvw" and if
int slashCounter=3,
The desired Output should be -
Output: abcdaa/efgh/hidjk/lmno

(Basically if slashCounter=3 only alplabets upto 4th '/' is allowed. From fourth '/'everything is ignored. Below is the few Input and Output. (There may be any number of alphabets between '/' to '/'). Below is few more inputs

Input:
String aaabcd/efgh/hidjk/lmno/pqrs/tuvw
if int slashCounter=2
Output: aaabcd/efgh/hidjk

Input:
String aaabcd/efgh/hidjk/lmno/pqrs/tuvw
if int slashCounter=4
Output: aaabcd/efgh/hidjk/lmno/pqrs

Could someone help me with the logic of this in JAVA. Thanks in advance.

TecnoEye
  • 25
  • 4
  • 2
    Does this answer your question? [How to find nth occurrence of character in a string?](https://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string) – Milgo Sep 28 '20 at 06:26
  • So, whats the concrete programming problem you are facing? – Polygnome Sep 28 '20 at 07:04

1 Answers1

-1

This is how you do.

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        // till how much we want the string
        int display = sc.nextInt();
        // splits the String when "/" is encounter and then stores it in 0 index and then increases the index
        String aplhabets[] = input.split("/");
        // to add the String we want 
        StringBuilder sb = new StringBuilder();
        for(int i = 0 ; i <= display; i++) {
            sb.append(aplhabets[i]+"/");
        }
        // as we dont want the last "/" of the String we just print from 0 to string length - 1, this will remove teh last "/"
        System.out.print(sb.substring(0, sb.length()-1));
    }

Output:

aaabcd/efgh/hidjk/lmno/pqrs/tuvw
2
aaabcd/efgh/hidjk

String aplhabets[] = input.split("/") this splits the String and puts it in the array whenever / is encounter.

sb.substring(0, sb.length()-1) this cause when we were appending String builder from he loop it's adding / in the end.
So in order to remove last / we do sb.substring(0,sb.length-1) where first parameter is start index and second index is end index
in substring(int start, int end) start in inclusive and end is exclusive.

this is how you do the problem. Suggest you learn how to use arrays and String manipulation. this will surely benefit you.

Swapnil Padaya
  • 687
  • 5
  • 14