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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23019070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:04:22  来源:igfitidea点击:

How to print only specific parts of a string in java?

javastringconcat

提问by CyborGamer

I am writing a program that writes a letter using specific parts of a string.

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

Here is what I have so far (I am only a beginner)

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

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

采纳答案by JeanLescure

The best you can do here is to split your Adress string, by commas, and grab the first value from the resulting array.

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

Take a look at this questionfor more details on splitting a string in Java.

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

I suggest the following in your code:

我建议在您的代码中执行以下操作:

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

Cheers!

干杯!

回答by ifloop

It would be a better style to use different variables for each part (city, postal and zip code).

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

Otherwise you might

否则你可能

  • Change the order of the elements, take postal into the middle and than do String city = Location.split("[0-9]")[0];
  • Define a token that the users inputs to seperate the data (e.g. #) and than do String city = Location.split(#`)[0];
  • 改变元素的顺序,把邮政放在中间,然后做 String city = Location.split("[0-9]")[0];
  • 定义用户输入的令牌以分隔数据(例如#)而不是String city = Location.split(#`)[0];

回答by David MacNeil

To break a string apart use this method

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

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

From here, you can find out which parts of the string you want.

从这里,您可以找出您想要的字符串的哪些部分。