简体   繁体   中英

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

I'm working on a school assignment for a hotline, and the output has to be a 1-800- number. I've worked out everything, but in the end, the requirement is that after 1-800- , I need to add another hyphen - in front of the third number after 1-800- . How would I go about that? I've worked out that the hyphen would come at the 9th index if that helps. ASCII determines the number output after the user inputs a string.

An example output would be:

Enter a string: help now
1-800-4357669

Process finished with exit code 0

In this case, the hyphen would come after the number 5 , which is the 9th index (since the number 5 is at the 8th index).

I'm new to java, so I haven't quite figured it out yet. Any help is appreciated.

I figured it out. I just split the string using the .substring() function and then joined the two splits with a hyphen.

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);

you had to elaborate on many thing like you would insert the hyphen in the 3rd index of the entered number or the 9th index, like whether the user would enter 1-800-4357669 or just 4357669 , also you didn't post your code, so there is so many missing details, anyways,this is my solution for your problem:

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");
        }
    }
}

this code is supposed to work with a number entered by the user and here is image of the result when I run the code: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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