英文:
Transform Values in Java String with Multiplier
问题
public String transformOutput(int x) {
String transformedString = string.replaceAll("\\d+", Integer.toString(Integer.parseInt("$0") * x));
return transformedString;
}
英文:
I am interested in multiplying all the numbers in a Java string by a parameter (x) as in the following example where x = 5.
Initial Input: "I have 10 tickets, 5 sodas and 20 snacks to sell."
Target Output: "I have 50 tickets, 25 sodas and 100 snacks to sell."
I tried the following code in Java, but it did not produce the 'Target Output'. I also tried to create a for loop iterating through the string and multiplying any numbers by (x) but this did not work either. How can one produce the desired output in Java?
public String transformOutput(int x){
string = string.replaceAll("\\d", "\\d" * n)
return string
}
答案1
得分: 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws Exception {
String input = "I have 10 tickets, 5 sodas and 20 snacks to sell.";
System.out.println(transformOutput(5, input));
}
public static String transformOutput(int x, String str) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, String.valueOf(Integer.parseInt(matcher.group()) * x));
}
matcher.appendTail(buffer);
return buffer.toString();
}
}
英文:
Get the numbers using regex and use Matcher.appendReplacement
to replace
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws Exception {
String input = "I have 10 tickets, 5 sodas and 20 snacks to sell.";
System.out.println(transformOutput(5, input));
}
public static String transformOutput(int x, String str) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(str);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, String.valueOf(Integer.parseInt(matcher.group()) * x));
}
matcher.appendTail(buffer);
return buffer.toString();
}
}
答案2
得分: 0
使用Java 8+的流:
public String transform(String input, int multiplicator) {
return Pattern.compile(" ")
.splitAsStream(input)
.map(token -> {
try {
return "" + multiplicator * Integer.parseInt(token.trim());
} catch (NumberFormatException e) {
return token;
}
})
.collect(Collectors.joining(" "));
}
@Test
public void test() {
String input = "I have 10 tickets, 5 sodas and 20 snacks to sell.";
String output = transform(input, 5);
assertEquals("I have 50 tickets, 25 sodas and 100 snacks to sell.", output);
}
英文:
Using Java 8+ streams:
public String transform(String input, int multiplicator) {
return Pattern.compile(" ")
.splitAsStream(input)
.map(token -> {
try {
return "" + multiplicator * Integer.parseInt(token.trim());
} catch (NumberFormatException e) {
return token;
}
})
.collect(Collectors.joining(" "));
}
@Test
public void test() {
String input = "I have 10 tickets, 5 sodas and 20 snacks to sell.";
String output = transform(input, 5);
assertEquals("I have 50 tickets, 25 sodas and 100 snacks to sell.", output);
}
答案3
得分: 0
以下是翻译好的内容:
这是一种方法来实现它。它的工作原理如下:
注意:根据您的示例,我假设您不希望数字嵌入在单词中(例如foo25)。
-
在一个或多个空格上拆分字符串。
-
流式传输随后的令牌数组。
-
如果令牌与所有数字匹配,则选择性地将令牌映射到该值,否则,只需原样返回该单词。这是通过使用
ternary(?:)
运算符完成的。表达式a ? b : c
表示如果a
为真,则执行b
,否则执行c
。.map(st -> st.matches("\\d+") ? (Integer.valueOf(st) * n) + "" : st)
<br>- 如果字符串
st
与数字匹配,则转换为整数并乘以n
。 - 否则只返回字符串。
- 如果字符串
-
然后使用
Collectors.join(" ")
将流连接成一个字符串- 使用提供的分隔符(在这种情况下为一个空格)进行连接拼接。
import java.util.Arrays;
import java.util.stream.Collectors;
String str =
"我有10张票,5杯苏打和20份零食要出售。";
String tstr = transformOutput(str, 5);
System.out.println(tstr);
public static String transformOutput(String str, int n) {
return Arrays
.stream(str.split("\\s+"))
.map(st -> st.matches("\\d+") ?
(Integer.valueOf(st) * n) + "" : st)
.collect(Collectors.joining(" "));
}
输出结果:
我有50张票,25杯苏打和100份零食要出售。
英文:
Here is one way to do it. It works as follows:
Note: Base on your example, I am assuming you don't want numbers embedded in words (e.g foo25).
-
Split the string on one or more spaces.
-
Stream the subsequent array of tokens.
-
selectively map the token to the value if it matches all digits,
otherwise, just return the word unscathed. This is done by using the
ternary(?:)
operator. The expressiona ? b : c
says ifa
is true, dob
, else doc
..map(st -> st.matches("\\d+") ? (Integer.valueOf(st) * n) + "" : st)
<br>- if the string, st, matches a number then convert to an integer and multiply by
n
. - otherwise just return the string.
- if the string, st, matches a number then convert to an integer and multiply by
-
Then join the stream into a string again using
Collectors.join(" ")
- takes a delimiter and joins concatenates using the supplied delimiter (in this case a space).
import java.util.Arrays;
import java.util.stream.Collectors;
String str =
"I have 10 tickets, 5 sodas and 20 snacks to sell.";
String tstr = transformOutput(str, 5);
System.out.println(tstr);
public static String transformOutput(String str, int n) {
return Arrays
.stream(str.split("\\s+"))
.map(st -> st.matches("\\d+") ?
(Integer.valueOf(st) * n) + "" : st)
.collect(Collectors.joining(" "));
}
Prints
I have 50 tickets, 25 sodas and 100 snacks to sell.
</details>
# 答案4
**得分**: -2
欢迎来到StackOverflow。你的想法很不错,使用正则表达式是有道理的,但不幸的是这样不起作用。替换函数确实可以找到所有要替换的数字,但只能用一个值来替换它们。
一个可行的方法是逐个查找所有的数字,然后进行替换。这似乎是一个作业题,所以我不会提供实际的解决方案,你已经非常接近了!
<details>
<summary>英文:</summary>
welcome to StackOverflow. The idea you have is good, using regex makes sense, but won't work like that unfortunately. The replace function does find all of the numbers to replace, but can only replace them with one value.
One approach that would work is to find all of the numbers individually, then replace them. This seems like a homework assignment, so im not going to provide an actual solution and your already quite close by yourself!
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论