繁体   English   中英

给定字符串长度,如何将输入作为字符串

[英]How to take input as String given the String Length

给定字符串长度,如何从用户输入作为字符串

问题链接:

http://www.practice.geeksforgeeks.org/problem-page.php?pid=295

我的方法:

我使用Scanner完成任务以获取测试用例的数量,然后将String长度作为输入:

但是我很困惑如何采用指定长度的字符串。我的搜索发现没有方法或构造函数可以采用指定长度的字符串。

有人可以指导吗?

下面是我的代码:

 Scanner sc=new Scanner(System.in);
 int T=sc.nextInt();
 for(int i=1;i<=T;i++)
  {
    int Strlength=sc.nextInt();
    String strnew=sc.next(); //How to take Stringofspecified character
    ..........
     .........
   }

您无法做到这一点,如果String的长度与给定的输入不匹配,您可以简单地迫使用户重新插入String。

 Scanner sc=new Scanner(System.in);
 int T=sc.nextInt();
 for(int i=1;i<=T;i++)
  {
    int Strlength=sc.nextInt();
    String strnew = null;
    while (strnew == null || strnew.size() != Strlength) {
      strnew = sc.next(); 
    }
    ..........
     .........
   }

一种方法是插入某种测试,例如:

String strnew;
do{
   strnew=sc.next(); //How to take Stringofspecified character
}
while(strnew.length() != Strlength);

我想出了一种方法。

Scanner sc = new Scanner(System.in);
int strLength = sc.nextInt();
sc.nextLine(); 
String strInput = sc.nextLine();
if(strInput.length()>strLength)
{
    str = str.substring(0, strlength);
}
// Now str length is equal to the desired string length
    String S = "";
    Scanner sc = new Scanner(System.in);
    int D = sc.nextInt();
    for(int i=0;i<D;i++) {
         S = S + sc.next();
    }
    System.out.println(S);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM