簡體   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