Decompose string to form a valid expression

## Decompose string to form a valid expression

string parse java
string.parse c#
parse string python
how to split a string by position in java
how to split a string in java with delimiter
string split python
parse string javascript
java split string by space

I am given a string S (of integers) and a number N. I want to insert arbitrary number of '+' in S so that the sum becomes equal to N.

```Ex:<br>
S = 15112 and N = 28<br>
Ans is : 15+11+2<br>
S = 120012 and N = 33<br>
Ans is : 1+20+012<br>
S = 123 and N = 123<br>
Ans is : 123
```

given : |S| <= 120 and N <= 10^6 It is guarenteed that S and N are given such that it is always possible to form valid expression. Is there any algorithm which can solve this? I tried to think on it but couldn't come up with solution.

The idea is to use dynamic programming, you only care about sums between 0 and 10^6 and only have 120 possible indexes. if dp[i][j] = x, it means that from index x of the string, we went to index i (so we added a + before i) and we got a sum of j. This leads to a O(|S| * N) solution:

```#include <iostream>
#include <string>
#include <vector>

using namespace std;

string s;
long n;

long dp;

void solve (int index, long sum) {//index = what index of s still remains to scan. sum = the sum we have accumulated till now
if (sum >= n or index >= s.length()) return;
if (dp[index][sum] != -1) return;
if (index == n and sum == n) return;

long num = 0;

for (int i = 0; i < 7 && index + i < s.length(); i++) { //N has 6 digits at most
num = stoi(s.substr(index, i + 1));
solve(index + i + 1, sum + num);
if (sum + num <= n) {
dp[index + i + 1][sum + num] = index;
}
}

}

int main () {
cin >> s;
cin >> n;

for (int i = 0; i < 121; i++) {
for (int j = 0; j < 1000001; j++) {
dp[i][j] = -1;
}
}

solve(0, 0);

int sum = n;
int idx = s.length();

vector<string> nums;
//reconstruct solution
while (idx != 0) {
nums.push_back(s.substr(dp[idx][sum], idx - dp[idx][sum]));
idx = dp[idx][sum];
sum -= stoi(nums[nums.size() - 1]);
}

for (int i = nums.size() -1; i >= 0; i--) {
cout << nums[i];
if (i != 0) cout << "+";
}

}
```

Parsing Strings with split, (This form is a kind of regular expression. You don't need to know about regular expressions - just use the template shown here.) The plus sign (+) is used to  The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string. To identify a string literal as an interpolated string, prepend it with the \$ symbol. You can embed any valid C# expression that returns a value in an interpolated string.

There may be more efficient ways to do this, but since you have nothing so far…

You can simply find all combinations of a boolean array that indicates whether a plus should exist between the numbers or not.

For example: with an input of `112134`, `1 + 12 + 13 + 4` can be represented with the boolean array `[true, false, true, false, true]` indicating that there is a plus after the 1st, 3rd, and 5th numbers. The problem then reduces to finding which combinations add to your number. There are lot of ways to find combinations. Recursive backtracking is a classic.

In javascript/node this might look like this:

```function splitOnIndexes(arr, a) {
// split the array into numbers based on the booleans
let current = "" + arr
let output = []
for (let i = 0; i < a.length; i++) {
if (!a[i]) {
current += arr[i + 1]
} else {
output.push(current)
current = "" + arr[i + 1]
}
}
output.push(current)
return output
}

function findSum(input, total) {
function backtrack(n, k = 0, a = []) {
const sum = (arr) => arr.reduce((a, c) => a + parseInt(c), 0)
if (k === n) {
let ans = splitOnIndexes(input, a)
if (sum(ans) === total) {
console.log(ans.join(' + '))
}
} else {
k = k + 1
let c = [true, false]
for (let i = 0; i < 2; i++) {
a[k - 1] = c[i]
backtrack(n, k, a)
}
}
}

backtrack(input.length - 1)
}

findSum('15112', 28)

findSum('120012', 33)

findSum('123', 123)```

How to parse strings using String.Split (C# Guide), String.Split returns an array of strings split from a set of delimiters. It's an easy way to The following code splits a common phrase into an array of strings for each word. C# Copy. Run Strings .NET Regular Expressions  The form is geared to post towards /. It is marked as being backed up by the personForm object that you saw in the GET method in the web controller. This is known as a bean-backed form. There are two fields in the PersonForm bean, and you can see them tagged th:field=" {name}" and th:field=" {age}".

This is a Ruby version with step by step explanation of the algorithm, so you can easily code in C++ (or I'll try later).

```# Let's consider that we extracted the values from text, so we already have the string of int and the result as integer:

string_of_int = "15112"
result = 28

# The basic idea is to find a map (array) that tells how to group digits, for example

sum_map = [2, 1, 2]

# This means that string_of_int is mapped into the following numbers
# 15, 1, 12
# then sum the numbers, in this case 15+1+12 = 28

# For finding a the solution we need to map
# all the possible combinations of addition given the n digits of the string_of_int then check if the sum is equal to the result

# We call k the number of digits of string_of_int
# in ruby we can build an array called sum_maps
# containing all the possible permutations like this:

k = string_of_int.length # => 5
sum_maps = []
k.times do |length|
(1..k).to_a.repeated_permutation(length).each {|e| sum_maps << e if e.inject(:+) == k}
end
sum_maps
# => [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [1, 1, 4], [1, 2, 3], [1, 3, 2], [1, 4, 1], [2, 1, 3], [2, 2, 2], [2, 3, 1], [3, 1, 2], [3, 2, 1], [4, 1, 1]]

# Now must check which of of the sum_map is giving us the required result.
#
# First, to keep the code short and DRY,
# better to define a couple of useful methods for the String class to use then:

class String
def group_digits_by(sum_map)
string_of_int_splitted = self.split("")
grouped_digits = []
sum_map.each { |n| grouped_digits << string_of_int_splitted.shift(n).join.to_i}
grouped_digits.reject { |element| element == 0 }
end

def sum_grouped_of_digits_by(sum_map)
group_digits_by(sum_map).inject(:+)
end
end

# So we can call the methods directly on the string
# for example, in ruby:

string_of_int.group_digits_by sum_map #=> [15, 1, 12]
string_of_int.sum_grouped_of_digits_by sum_map #=> 28

# Now that we have this metods, we just iterate through the sum_maps array
# and apply it for printing out the sm_map if the sum of grouped digits is equal to the result
# coded in ruby it is:

combinations = []
sum_maps.each { |sum_map| combinations << string_of_int.group_digits_by(sum_map) if string_of_int.sum_grouped_of_digits_by(sum_map) == result }
p combinations.uniq
# => [[15, 1, 12], [15, 11, 2]]
```

In short, written as a Ruby module it becomes:

```module GuessAddition
class ::String
def group_digits_by(sum_map)
string_of_int_splitted = self.split("")
grouped_digits = []
sum_map.each { |n| grouped_digits << string_of_int_splitted.shift(n).join.to_i}
grouped_digits.reject { |element| element == 0 }
end
def sum_grouped_of_digits_by(sum_map)
group_digits_by(sum_map).inject(:+)
end
end
def self.guess_this(string_of_int, result)
k = string_of_int.length
sum_maps = []
k.times { |length| (1..k).to_a.repeated_permutation(length).each {|e| sum_maps << e if e.inject(:+) == k} }
combinations = []
sum_maps.each { |sum_map| combinations << string_of_int.group_digits_by(sum_map) if string_of_int.sum_grouped_of_digits_by(sum_map) == result }
combinations.uniq
end
end

p GuessAddition::guess_this("15112", 28) # => [[15, 1, 12], [15, 11, 2]]
```

Java String split() Method with examples, It throws PatternSyntaxException if the syntax of specified regular expression is not valid. Java String split Example. public class SplitExample{  Gets or sets the regular expression that determines the pattern used to validate a field. A string that specifies the regular expression used to validate a field for format. The default is Empty. The regular expression is not properly formed. The following example demonstrates how to use the ValidationExpression property to validate a field

Python String, split() method returns a list of strings after breaking the given string by the specified separator. Syntax : str.split(separator, maxsplit). Parameters : separator : The  assigns the string "lo world" into the variable subs. The first parameter must indicate a valid position within the string (similar to the case of the starting position for find, discussed earlier), or the behaviour is undefined. The second parameter, combined with the first one, can be such that the length of the string is exceeded.

Split() String method in Java with examples, Parameters: regex - a delimiting regular expression Limit - the result threshold Returns: An array of strings computed by splitting the given string. Throws:  In slicing, if the end index specifies a position beyond the end of the string, Python will use the length of the string instead. An expression of the form string [i] = 'i' is a valid expression. If the + operator is used on strings, it produces a string that is the combination of the two strings used as its operands.

Java String split() method example, The Java String split() returns string array after it splits the string around matches of the method argument regular expression or delimiter(s). In this tutorial, we learned how to add basic validation to our forms by simply using HTML and regex. Using the right value for the type attribute will force users to enter information in an input field in a certain format. Use of regular expressions with the pattern attribute can help us keep the valid input more constrained.