在java中,如何从字符串的第一个字符中删除字符串值?

nxowjjhe  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(385)

我想从mobilenumber中删除countrycode,它只包含前三个字符的+91。

String countrycode = +91;

String mobileNumber = 123917890;

if (mobileNumber.contains(countrycode)){
    int v = countrycode.length();
    String phonenumber = mobileNumber.substring(v);
    System.out.println(phonenumber);
} else {
    System.out.println("mobile number doesn't have country code");
}

但在mycode中,如果mobilenumber包含在整个字符串中,它将从mobilenumber中删除91。
获取输出:

3917890

但是如果包含三个字符,我想在第一个字符串中删除countrycode。我应该如何创造这种条件?

cdmah0mi

cdmah0mi1#

如果找到,可以使用字符串替换将+91替换为空白

String countrycode = +91;

String mobileNumber = 123917890;

String noCountryCode = mobileNumber.replace("+91", "");

System.out.println(noCountryCode);
8xiog9wr

8xiog9wr2#

你得打电话 .substringmobileNumber 而不是开着 num_code .
演示:

class Main {
    public static void main(String[] args) {
        String countrycode = "+91";

        // Test numbers
        String[] mobileNumbers = { "+91123917890", "123917890" };

        for (String mobileNumber : mobileNumbers) {
            if (mobileNumber.contains(countrycode)) {
                int v = countrycode.length();
                String phonenumber = mobileNumber.substring(v);
                System.out.println(phonenumber);
            } else {
                System.out.println("mobile number doesn't have country code");
            }
        }
    }
}

输出:

123917890
mobile number doesn't have country code
mfpqipee

mfpqipee3#

我得到了答案,谢谢大家对我的帮助
很简单

String countrycode = +91;

String mobileNumber = 123917890;

if (mobileNumber.contains("+" + countrycode)){
                    int v = countrycode.length();
                    String phonenumber = num_code.substring(v);
                    System.out.println(phonenumber);
                } else {
                    System.out.println("mobile number doesn't have country code");
                }

现在它正在按预期的结果工作。

相关问题