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

标签 java string concatenation

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

这是我目前所拥有的(我只是一个初学者)

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

最佳答案

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

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

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

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

干杯!

关于java - 如何在 java 中只打印字符串的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23019070/

相关文章:

java - 所采用的点是 gradle 脚本中的正斜杠

sql - 替换 SQL 中的字符串值

r - 在 R 中查找字符串中连续重复项的索引

java - 如何从 .jar 文件加载 PDF?

java - 如何通过方法实现动态查找类?

java - java中的null或空字符串比较?或者是其他东西?

python - 为什么我的链接提取不起作用?

sql - 添加一个表示其他两个Varchar列的串联的列

python - 将两个数据框与一些公共(public)列合并,其中公共(public)列的组合需要自定义函数

java - 为什么我不能在函数内使用 ManagedProperty ?