简体   繁体   中英

How to take input as String given the String Length

How to take input from User as String given the String Length

The problem link:

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

MyApproach:

I used Scanner for the task to take the number of testcases and then took the String length as input:

But I am confused how to take String of specified length.My search found that there is no method or constructor which can take string of specified length.

Can Anyone guide?

Below is my code:

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

You can't do that, you can simply force the user to reinsert the String if the length of the String does not match the given input.

 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(); 
    }
    ..........
     .........
   }

A way to do this is inserting some kind of test, eg:

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

I figured out a way to do this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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