繁体   English   中英

用句点替换所有逗号,反之亦然?

[英]Replace all commas with periods and vice versa in a string?

如果可能,尝试使用 Kotlin 序列一次性弄清楚如何做到这一点。 我不认为基于 Locale 的数字格式是可能的,因为我有时会有像 1. 或 1, 那样抛出 NumberFormatException 的字符串。 需要在没有任何数字转换的情况下执行此操作。

  • 12,345.6789 -> 12.345,6789
  • 12.345,6789 -> 12,345.6789
  • . ->,
    1. -> 1,

一通。 不使用任何 Kotlin,我只能写 Java。

    String s = "12,345.6789";
    char[] ca = s.toCharArray();
    for (int i = 0; i < ca.length; i++) {
        if (ca[i] == '.') {
            ca[i] = ',';
        } else if (ca[i] == ',') {
            ca[i] = '.';
        }
    }
    s = new String(ca);
    System.out.println(s);

Output:

12.345,6789

这是相当低级的,所以请把它包装成一个名字好听的方法。 否则我认为这是直截了当的。 如果您更喜欢使用StringBufferStringBuilder ,这些也是选项。

不过,如果那是我,我会再考虑一下号码解析和格式化。

您可以在String上使用map function 并使用joinToString()转换结果List<Char> 这是一次替换,但必须将其复制回字符串。

fun String.swapCommasAndDots() = map { c ->
    when (c) {
        ',' -> '.'
        '.' -> ','
        else -> c
    }
}.joinToString("")

这可能是一个非常幼稚的解决方案,但如果您知道您的字符串中只有数字,这将起作用。

var oldString = "12,345.6789"
var newString = oldString
    .replace('.', 'x')
    .replace(',', '.')
    .replace('x', ',')
print(newString)
// 12.345,6789

您可以将一个字符替换为未使用的字符:

String str = "1234.123213,414";
str = str.replace(",", "+");
str = str.replace(".", ",");
str = str.replace("+", ".");
System.out.println("str = " + str); 
// Output: str = 1234,123213.414

您可以为此目的使用此代码:-

String num = "12,345.6789";
//Replacing all '.' to '}' Just for the sake of simplicity
String transformednum = num.replace('.', '}');
//Replacing all ',' to '.'  First Thing you want
transformednum = transformednum.replace(',', '.');
//Replacing all '}' to ','   Second thing you want 
transformednum = transformednum.replace('}', ',');
System.out.println(transformednum);

希望这会有所帮助。

    String in = "12,345.6789";

    Pattern p = Pattern.compile("[,.]");
    Matcher m = p.matcher(in);
    StringBuilder sb = new StringBuilder();

    while (m.find()) {
        m.appendReplacement(sb, m.group().equals(".") ? "," : ".");
    }

    m.appendTail(sb);

    System.out.println(sb.toString());
String::replaceAll(a, b)

可以将任何出现的 substring a替换为 substring b

但是,要进行交换,您需要应用此方法 3 次,如下所示:

String number = "123,456.05";
number = number.replaceAll(",", "&").replaceAll(".", ",").replaceAll("&", ".");

一般来说,交换字符是这样的:

  1. 您将逗号替换为占位符 substring (可以是任何东西,真的)
  2. 你把所有的点都转换成逗号
  3. 您将占位符转换为点。

如果不是占位符,你最终会得到所有逗号。

number.replaceAll(",", ".").replaceAll(".", ",");
//this would transform commas into dots, then the same transformed commas would become commas again.

如何使用流:

static String swapChars(String str, String c1, String c2)
{
    return Stream.of(str.split(c1, -1))
          .map (elem -> elem.replace(c2, c1))
          .collect(Collectors.joining(c2));
}

测试:

for(String s : new String[] {"12,345.6789", "12.345,6789", ".", "1." ,"1,"})
    System.out.format("%s -> %s%n", s, swapChars(s, ",", ".") );

Output:

12,345.6789 -> 12.345,6789
12.345,6789 -> 12,345.6789
. -> ,
1. -> 1,
1, -> 1.

只需使用String::replace如下:

public class Main {
    public static void main(String args[]) {
        // Tests
        System.out.println(swapCommaWithDot("1,123,345.6789"));
        System.out.println(swapCommaWithDot("1.123.345,6789"));
    }

    static String swapCommaWithDot(String n) {
        return n.replace(",", ",.").replace(".", ",").replace(",.", ".").replace(",,", ".");
    }
}

Output:

1.123.345,6789
1,123,345.6789

暂无
暂无

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

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