简体   繁体   中英

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

Trying to figure out how to do this in one pass using Kotlin sequences if possible. I don't think number formatting based on Locale is possible since I sometimes have strings that would throw NumberFormatException like 1. or 1, . Need to do this without any number transformations.

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

In one pass. Not using any Kotlin, I can write only 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

It's pretty low-level, so please wrap it into a method with a nice name. Otherwise I think it's straight-forward. If you prefer to use a StringBuffer or StringBuilder , those are options too.

I'd giver number parsing and formatting one more thought if that was me, though.

You can use the map function on a String and convert the resulting List<Char> with joinToString() . It's one pass for replacement, but it has to be copied back into a String.

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

This might be a very naive solution but if you know you'll only have numbers in your string this would work.

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

You could replace one character with something not used:

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

You can use this code for that purpose:-

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

Hope this will help.

    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)

can replace any occurrences of the substring a for the substring b .

However, to do the swap you need to apply this method three times, like so:

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

Generally, to swap characters it's like this:

  1. you replace the comma for a placeholder substring (can be anything, really)
  2. you convert all the dots into commas
  3. you convert the placeholders into dots.

If it wasn't for the placeholder, you'd end up with all commas.

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

How about using Streams:

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

Test:

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.

Simply use String::replace as follows:

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

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