2017-02-04 98 views
0

我需要一個解析輸入字符串(電子郵件地址)並以規範化格式打印的程序。它應該有3個由','分隔的部分,如下所示:Int,Int,String前兩個整數部分表示程序應該提取的子字符串的第一個和最後一個字符的索引。 例如,假設我輸入以下內容作爲輸入:0,6,alex.da @ yahoo.com =>輸出應該變成=> alex.da 有誰知道如何做到這一點?如何解析輸入字符串並以規範化形式打印? (Java)

import java.util.Scanner; 
public class Labs02 { 
public static void main(String[] args) { 

Scanner stdIn = new Scanner(System.in); 

    System.out.println("enter your Email:"); 
    String response = stdIn.nextLine(); 

    String first=response.substring(0,1); 
    int second=response.indexOf(response.charAt(2)); 
    System.out.println(response.substring(response.indexOf(response.substring(0, 1))+4));  
    } //This is where I get stuck! 
+0

刪除了JavaScript代碼。 –

回答

0

分割使用,,然後整個字符串解析起2串獲得位置和第三串像下面適用String#subString

String response = stdIn.nextLine(); 
String arr[] = response.split(","); // this will make three strings as "0" , "6", "[email protected]" 
int first=Integer.parseInt(arr[0]); 
int second=Integer.parseInt(arr[1]); 
System.out.println(arr[2].substring(first, second + 1); 
+0

對於@Henry我補充了另外一種方式,謝謝 –

+0

@sarah這種方法更安全,使用這個 –

+1

非常感謝!對此,我真的非常感激。 – sarah

0

首先,你需要輸入字符串分隔成其結構部件通過使用逗號作爲分隔符:

List<String> paramaters = Arrays.asList(response.split(",")); 

然後你需要提取子按您的要求:

String first = response.substring(Integer.parseInt(paramaters[0]),Integer.parseInt(parameters[1])); 

變量首先會保存你的子串。

+0

'get(int index)'方法用於'List'中的隨機訪問。 –

+0

對我的壞,我只是在編輯中輸入,沒有ide指出。但也會起作用。 – Harriet