繁体   English   中英

如果我想在字符串中的特定 position 添加特定字符,我将如何处理 go 呢? [爪哇]

[英]If I wanted to add a specific character at a specific position in a string, how would I go about that? [Java]

我正在为热线电话分配学校作业, 1-800-必须是 1-800 号码。 我已经解决了所有问题,但最后,要求是在1-800-之后,我需要在1-800-之后的第三个数字前面添加另一个连字符- 我怎么会 go 呢? 我已经计算出,如果有帮助的话,连字符会出现在第 9 个索引处。 用户输入字符串后,ASCII 确定数字 output。

例如 output 将是:

Enter a string: help now
1-800-4357669

Process finished with exit code 0

在这种情况下,连字符将出现在数字5之后,即第 9 个索引(因为数字5在第 8 个索引处)。

我是 java 的新手,所以我还没有完全弄清楚。 任何帮助表示赞赏。

我想到了。 我只是使用.substring() function 拆分字符串,然后用连字符连接两个拆分。

String string1 = final_number_temp.substring(0,9);
String string2 = final_number_temp.substring(9);
String final_number = string1 + "-" + string2;

System.out.println(final_number);

您必须详细说明许多事情,例如您将在输入数字的第三个索引或第 9 个索引中插入连字符,例如用户是输入1-800-4357669还是仅输入4357669 ,您也没有发布您的代码,所以有很多缺失的细节,无论如何,这是我对你的问题的解决方案:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        String basicNum = "1-800";
        String dummyString;

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a string:");
        dummyString = scanner.nextLine();

        System.out.println("Enter a number");
        dummyString = scanner.nextLine();

        try
        {
            int enteredNum = Integer.parseInt(dummyString); // -> throws NumberFormatException if entered value isn't integer
            int enteredNumLen = String.valueOf(enteredNum).length();
            int firstPart = (int) (enteredNum / Math.pow(10 , (enteredNumLen - 3)));
            int secondPart = (int) (enteredNum % Math.pow(10 , (enteredNumLen - 3)));
            basicNum = String.format("%s-%d-%d", basicNum, firstPart, secondPart);
            System.out.println(basicNum);
        }catch (NumberFormatException numberFormatException){
             // do whatever here to handle if the entered value isn't integer
            System.out.println("not valid number");
        }
    }
}

此代码应该与用户输入的数字一起使用,这是我运行代码时的结果图像: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM