[英]How to print only specific parts of a string in java?
我正在編寫一個程序,使用字符串的特定部分寫一封信。
這是我到目前為止(我只是一個初學者)
import java.util.Scanner;
public class AutoInsurance {
public static void main (String[] args)
{
Scanner scan=new Scanner (System.in);
System.out.print("Enter Name:");
String Name;
Name=scan.nextLine();
System.out.print("Enter Street Address:");
String Address;
Address=scan.nextLine();
System.out.print("Enter city, state, and zip code:");
String Location;
Location=scan.nextLine();
System.out.println();
System.out.println();
System.out.println("Dear "+Name+",");
System.out.println(" You have been selected to receive this offer of auto insurance from");
System.out.println("Allspam Insurance Company! Drivers from "++" saved an average "); // I just want it to print the city here, between ++
// I will finish coding once I figure this out, but I'm stumped
}
}
你可以做的最好的事情是用逗號分割你的地址字符串,並從結果數組中獲取第一個值。
有關在Java中拆分字符串的更多詳細信息,請查看此問題 。
我在您的代碼中建議以下內容:
String[] AddressParts = Address.split(",");
String City = AddressParts[0];
System.out.println("Allspam Insurance Company! Drivers from "+City+" saved an average ");
干杯!
對每個部分(城市,郵政和郵政編碼)使用不同的變量將是一種更好的方式。
否則你可能會
String city = Location.split("[0-9]")[0];
#
),而不是String city = Location.split(
#`)[0]; 要打破字符串,請使用此方法
String s = "abcde";
String p = s.substring(2, s.length);
從這里,您可以找到所需字符串的哪些部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.