I have a string (mathematical equation):
Wt=mgt
This is what I would like to split them by: ['wt', 'm', 'g', 't']
I would like the result ['Wt', '=', 'm', 'g', t']
I am not sure how to do this.
Clarification:
This should be applicable to all equations inputted. My goal is to have the user input an equation and an array, and split the string into a another array using the initial array they gave me:
split('Wt=mg', ['Wt', 'm', 'g']) // => ['Wt', '=', 'm', 'g']
split('maa=tna', ['ma', 'a', 't', 'n']) // => ['ma', 'a', '=', 't', 'n', 'a']
split('Fnet=ma', ['Fnet', 'm', 'a']) // => ['Fnet', '=', 'm', 'a']
CodePudding user response:
For the first case you can use something like this.
let str = "Wt=mgt"
let strArr = str.split("=")
let res = [strArr[0], ...strArr[1].split("")];
console.log(res)
For the second result you can use the above method and just insert the "=" in between.
let str = "Wt=mgt"
let strArr = str.split("=")
let res = [strArr[0],"=", ...strArr[1].split("")];
console.log(res)
CodePudding user response:
I'm not a master on RegEx
so maybe there is a more elegant way to do this, but try this, it seems to work ok with your values:
console.log(splitStr('Wt=mg', ['Wt', 'm', 'g'])) // => ['Wt', '=', 'm', 'g']
console.log(splitStr('maa=tna', ['ma', 'a', 't', 'n'])) // => ['ma', 'a', '=', 't', 'n', 'a']
console.log(splitStr('Fnet=ma', ['Fnet', 'm', 'a'])) // => ['Fnet', '=', 'm', 'a']
function splitStr(string, array){
const matches = "(" array.join("|") "|=)"
return string.split(new RegExp(matches)).filter(f => f != '')
}
The trick here is to create a regex with stucture (value1|valueN|=)
with all values in the array and then split by these values.
CodePudding user response:
I am not entriely sure what your requirement here but you can do something like this:
List<String> final = new ArrayList<String>();
String toAdd = "";
for (int i = 0; i < s.length(); i ){
int c = (int) s.charAt(i);
if((c > 32 && c < 47) || (c > 58 && c < 64) || (c > 91 && c < 96) || (c > 123 && c < 126)){
final.push(toAdd);
final.push(s.charAt(i));
}
else{
toAdd = s.charAt(i);
}
}