用Java字符串中的乘法器转换值

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

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 -&gt; st.matches(&quot;\\d+&quot;) ? (Integer.valueOf(st) * n) + &quot;&quot; : st) <br>

    • 如果字符串st与数字匹配,则转换为整数并乘以n
    • 否则只返回字符串。
  • 然后使用Collectors.join(&quot; &quot;) 将流连接成一个字符串

    • 使用提供的分隔符(在这种情况下为一个空格)进行连接拼接。
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 -&gt; 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 expression a ? b : c says if a is true, do b, else do c.

    .map(st -&gt; st.matches(&quot;\\d+&quot;) ? (Integer.valueOf(st) * n) + &quot;&quot; : st) <br>

    • if the string, st, matches a number then convert to an integer and multiply by n.
    • otherwise just return the string.
  • Then join the stream into a string again using Collectors.join(&quot; &quot;)

    • 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 =                                                 
		&quot;I have 10 tickets, 5 sodas and 20 snacks to sell.&quot;; 
String tstr = transformOutput(str, 5);                       
System.out.println(tstr);                                    
                                                              
                                                                 
public static String transformOutput(String str, int n) {        
	return Arrays                                                
			.stream(str.split(&quot;\\s+&quot;))                           
			.map(st -&gt; st.matches(&quot;\\d+&quot;) ?                      
					(Integer.valueOf(st) * n) + &quot;&quot; : st)         
			.collect(Collectors.joining(&quot; &quot;));                   
	                                                             
}

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&#39;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>



huangapple
  • 本文由 发表于 2020年9月1日 04:32:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63677809.html
匿名

发表评论

匿名网友

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

确定