4

Given a string and an integer value x, return a new string with the first x characters of the original string now at the end. Make sure there are enough characters before attempting to move them to the end of the string.

Sample Data : Data File: stringChopper.dat

apluscompsci 3
apluscompsci 5
apluscompsci 1
apluscompsci 2
apluscompsci 30
apluscompsci 4

Sample Output : (output needs to be exact)

uscompsciapl
compsciaplus
pluscompscia
luscompsciap
no can do
scompsciaplu

My code:

public class StringChopperRunner_Cavazos {
   public static void main(String[] args) throws IOException {
      Scanner fileIn = new Scanner(new File("stringChopper.dat"));

      while(fileIn.hasNext()) {
      System.out.println(StringChopper.chopper(fileIn.next(), fileIn.nextInt()));
      }
   }
}

class StringChopper { 
   public static String chopper(String word1, int index) {
      if(word1.length() < index - 1){
         return "no can do";
      }
      else {
         return word1;
      } 
   }
}

So my question is; How can I return the String with the index number indicated if it's less than that to make sure there are ENOUGH letters printed?

1 Answer 1

2

Use String#substring to find different portions of a String and then concatenate them together using the + operator.

if (word1.length() < index - 1){
    return "no can do";
} else {
    return word1.substring(index) + word1.substring(0, index);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why does this question have three upvotes (currently) when it appears to me to be nothing more than an absolute basic homework question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.