如何在java中只打印字符串的特定部分?

时间:2014-04-11 17:33:09

标签: java string concat

我正在编写一个程序,使用字符串的特定部分写一封信。

这是我到目前为止(我只是初学者)

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

3 个答案:

答案 0 :(得分:3)

你可以做的最好的事情就是用逗号分割你的地址字符串,并从结果数组中获取第一个值。

有关在Java中拆分字符串的更多详细信息,请查看this question

我在您的代码中建议以下内容:

String[] AddressParts = Address.split(",");
String City = AddressParts[0];
System.out.println("Allspam Insurance Company! Drivers from "+City+" saved an average ");

干杯!

答案 1 :(得分:0)

对每个部分(城市,邮政和邮政编码)使用不同的变量将是一种更好的风格。

否则你可能

  • 更改元素的顺序,将邮件带到中间,然后执行String city = Location.split("[0-9]")[0];
  • 定义用户输入的标记以分隔数据(例如#)而不是String city = Location.split(#`)[0];

答案 2 :(得分:0)

要拆分字符串,请使用此方法

    String s = "abcde";
    String p = s.substring(2, s.length);

从这里,您可以找到所需字符串的哪些部分。