【问题标题】:If-Else stringsIf-Else 字符串
【发布时间】:2018-03-25 17:08:45
【问题描述】:

给定一个字符串和一个整数值 x,返回一个包含前 x 个字符的新字符串 原来的字符串现在在最后。确保之前有足够的字符 试图将它们移动到字符串的末尾。

样本数据: 数据文件:stringChopper.dat

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

样本输出:(输出需要准确)

uscompsciapl
compsciaplus
pluscompscia
luscompsciap
no can do
scompsciaplu

我的代码:

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;
      } 
   }
}

所以我的问题是;如果小于该索引号,如何返回带有指示的索引号的字符串以确保打印了足够的字母?

【问题讨论】:

    标签: java string if-statement


    【解决方案1】:

    使用String#substring 查找字符串的不同部分,然后使用+ 运算符将它们连接在一起。

    if (word1.length() < index - 1){
        return "no can do";
    } else {
        return word1.substring(index) + word1.substring(0, index);
    }
    

    【讨论】:

    • 为什么这个问题(目前)在我看来不过是一个绝对的基本作业问题?
    猜你喜欢
    • 2014-05-20
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多