如何在Android/Java中将字符串和数字后缀连接在一起?

huangapple go评论79阅读模式
英文:

How to join string and number suffixes together in Android/Java?

问题

// code in GeneralUtils.java file

public static String extractNumber(final String str) {
  if (str == null || str.isEmpty()) return "";
  StringBuilder sb = new StringBuilder();
  boolean found = false;
  for (char c: str.toCharArray()) {
    if (Character.isDigit(c)) {
      sb.append(c);
      found = true;
    } else if (found) {
      break;
    }
  }
  return sb.toString();
}

private static final NavigableMap<Long, String> thousandSuffixes = new TreeMap<>();

static {
  thousandSuffixes.put(1_000L, "k");
  thousandSuffixes.put(1_000_000L, "M");
  thousandSuffixes.put(1_000_000_000L, "G");
  thousandSuffixes.put(1_000_000_000_000L, "T");
  thousandSuffixes.put(1_000_000_000_000_000L, "P");
  thousandSuffixes.put(1_000_000_000_000_000_000L, "E");
}

public static String formatSuffixes(long value) {
  if (value == Long.MIN_VALUE) return formatSuffixes(Long.MIN_VALUE + 1);
  if (value < 0) return "-" + formatSuffixes(-value);
  if (value < 1000) return Long.toString(value);
  Map.Entry<Long, String> e = thousandSuffixes.floorEntry(value);
  Long divideBy = e.getKey();
  String suffix = e.getValue();
  long truncated = value / (divideBy / 10);
  boolean hasDecimal = truncated < 100 && (truncated / 10d) != (truncated / 10);
  return hasDecimal ? (truncated / 10d) + suffix : (truncated / 10) + suffix;
}
// code to get the result from those functions above

String product = productCategory.getProductName();
String number = GeneralUtils.extractNumber(product);
String formattedString = GeneralUtils.formatSuffixes(Long.valueOf(number));
Log.e("numberMatches", "numberMatches: " + number);
Log.e("formattedString", "formattedString: " + formattedString);

To join the formatted string with the strings before and after, and get the desired result in Android:

String result = "Recharge Data " + formattedString + " only in your location";

The result string will be: "Recharge Data 100K only in your location".

英文:

Well, I need to split a string, number, and the other string in order to get results with suffixes. I have this example string:

> Recharge Data 100000 only in your location

I was able to get this Log from the string above with this function in Java:

> E/numberMatches: numberMatches: 10000
>
> E/formattedString: formattedString: 10k

Here is the code of convert to suffixes string function:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// code in GeneralUtils.java file
public static String extractNumber(final String str) {
if (str == null || str.isEmpty()) return &quot;&quot;;
StringBuilder sb = new StringBuilder();
boolean found = false;
for (char c: str.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
found = true;
} else if (found) {
break;
}
}
return sb.toString();
}
private static final NavigableMap &lt; Long, String &gt; thousandSuffixes = new TreeMap &lt; &gt; ();
static {
thousandSuffixes.put(1 _000L, &quot;k&quot;);
thousandSuffixes.put(1 _000_000L, &quot;M&quot;);
thousandSuffixes.put(1 _000_000_000L, &quot;G&quot;);
thousandSuffixes.put(1 _000_000_000_000L, &quot;T&quot;);
thousandSuffixes.put(1 _000_000_000_000_000L, &quot;P&quot;);
thousandSuffixes.put(1 _000_000_000_000_000_000L, &quot;E&quot;);
}
public static String formatSuffixes(long value) {
if (value == Long.MIN_VALUE) return formatSuffixes(Long.MIN_VALUE + 1);
if (value &lt; 0) return &quot;-&quot; + formatSuffixes(-value);
if (value &lt; 1000) return Long.toString(value);
Map.Entry &lt; Long, String &gt; e = thousandSuffixes.floorEntry(value);
Long divideBy = e.getKey();
String suffix = e.getValue();
long truncated = value / (divideBy / 10);
boolean hasDecimal = truncated &lt; 100 &amp;&amp; (truncated / 10 d) != (truncated / 10);
return hasDecimal ? (truncated / 10 d) + suffix : (truncated / 10) + suffix;
}

<!-- end snippet -->

and here's the code to get the result from those function above:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

String product = productCategory.getProductName();
String number = GeneralUtils.extractNumber(product);
String formattedString = GeneralUtils.formatSuffixes(Long.valueOf(number));
Log.e(&quot;numberMatches&quot;, &quot;numberMatches: &quot; + number);
Log.e(&quot;formattedString&quot;, &quot;formattedString: &quot; + formattedString);

<!-- end snippet -->

How do I join the formatted string with the string before and its after to get a result look like this in Android?

> Recharge Data 100K only in your location

Any help will be much appreciated.

Thank you.

答案1

得分: 1

使用 String.replaceAll 将出现的 number 替换为 formattedString

String newProduct = product.replaceAll("\\b" + number + "\\b", formattedString);

请注意,number 应该被单词边界包围(如此处所示),以确保您不会意外地替换例如 10001000000 起始部分,从而得到 1k000

您可以在字符串中进行多个替换,使用 Matcher

Pattern pattern = Pattern.compile("\\d+");  // 只需执行一次,将其存储为常量。

Matcher m = pattern.matcher(product);
StringBuffer sb = new StringBuffer();
while (m.find()) {
  String number = m.group();
  String formattedString = GeneralUtils.formatSuffixes(Long.valueOf(number));

  m.appendReplacement(sb, formattedString);
}
m.appendTail(sb);

String newProduct = sb.toString();
英文:

Use String.replaceAll to replace occurrences of number with formattedString:

String newProduct = product.replaceAll(&quot;\\b&quot; + number + &quot;\\b&quot;, formattedString);

Note that number should be surrounded by work breaks (as shown here) to ensure you don't accidentally replace, say, the 1000 and the start of 1000000 and get 1k000.

You can do multiple replacements in a string using a Matcher:

Pattern pattern = Pattern.compile(&quot;\\d+&quot;);  // Do this once, store in a constant.
Matcher m = pattern.matcher(product);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String number = m.group();
String formattedString = GeneralUtils.formatSuffixes(Long.valueOf(number));
m.appendReplacement(sb, formattedString);
}
m.appendTail(sb);
String newProduct = sb.toString();

huangapple
  • 本文由 发表于 2020年8月27日 23:44:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63619651.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定