【问题标题】:How to print only specific parts of a string in java?如何在java中只打印字符串的特定部分?
【发布时间】:2014-05-25 23:47:45
【问题描述】:

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

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

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

【问题讨论】:

  • 当你得到用户的输入时,为什么不把城市保存到不同的变量中
  • 您必须根据输入方式拆分位置...我建议您为每个信息(城市/州/邮政编码)执行 scan.nextLine() 除非您建立明确的方式拆分字符串(分隔符),但用户可能会感到困惑并添加额外的不需要的字符
  • 我需要将城市、州和邮编保存在同一个字符串中,否则我必须让它们输入三个不同的变量。有没有办法可以做到这一点,但保持相同的格式?
  • @CyborGamer 您是否尝试过类似 While(Scan.hasNext()) 并以这种方式分配变量?

标签: java string concat


【解决方案1】:

使用此方法将字符串分开

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

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

如果你只想要 n 个字符,你也可以像这样使用 StringUtils:

StringUtils.substring("abcde", 0, 2) => "ab"      

【讨论】:

    【解决方案2】:

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

    否则你可能会

    • 改变元素的顺序,把post放到中间,然后String city = Location.split("[0-9]")[0];
    • 定义用户输入的令牌以分隔数据(例如#),而不是String city = Location.split(#`)[0];

    【讨论】:

    • 如果你住在纽约,我想这不会很好。
    • @pzaenger 对。没想到那个!
    【解决方案3】:

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

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

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

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

    干杯!

    【讨论】:

    • 非常感谢您提供的所有帮助!我没想到这么快的帮助!谢谢!
    • 没问题,这就是 StackExchange 社区的目的,一旦你实现了你想要的,一定要选择一个答案并投票(如果可能的话)。还要记住选择更适合问题的答案,即使你的目标随着你收到更多的输入而改变。好摆脱;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 2021-04-28
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多