Convert js function to python functions does't work - javascript

I have found an algorithm written in js (That I don't know how to code with) then I tried to convert it to python after a conversation with some friends who know js
Javascript
function crack(code) {
var N = '';
var M = '';
for(var i = 0; i < code.length; i++) {
if(i%2 == 0) {
N += code[i];
} else {
M = code[i] + M;
}
}
var key = N + M;
key = window.atob(key);
key = key.substring(2);
return key;
}
Python
import base64
def crack(code):
N = ''
M = ''
i = 0
for letter in code:
i =code.find(letter)
if i%2 == 0:
N += code[i]
else:
M =code[i] + M
key = N + M
key = base64.b64decode(key)
key = key[2:]
print key
As you can see it's the same code but the problem here that not give the same result !!
The string here to try on is:
N=m=NAobdtHRRHwaOuiU8mvcZhWddH5bZhz1MWzLapyR5nibbhG19ynccl3RBXvediCV5mjcbh2d0HubZhW1cWvLM4j8ACxONwi8
After searching for a while about window.atob found this method decodes a string of data which has been encoded by the btoa() method.
Then searched about btoa found this method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.
Now what to do to get the same result with python ??

No. It's not the same code.
for(var i = 0; i < code.length; i++) {
if(i%2 == 0) {
is NOT the same as
for letter in code:
i =code.find(letter)
if i%2 == 0:
What happens if all letters in the code is the same?
I didn't look further than this.
I recommend doing a "literal" translation first, and THEN attempting a "Pythonic" modification to the code.

You are searching for the first occurrence of letter in the code, in the line i =code.find(letter). As you want the index, I recommend using enumerate
Result:
import base64
def crack(code):
N = ''
M = ''
i = 0
for i, letter in enumerate(code):
if i%2 == 0:
N += code[i]
else:
M =code[i] + M
key = N + M
key = base64.b64decode(key)
key = key[2:]
print key
Seems correct:
>>> crack('N=m=NAobdtHRRHwaOuiU8mvcZhWddH5bZhz1MWzLapyR5nibbhG19ynccl3RBXvediCV5mjcbh2d0HubZhW1cWvLM4j8ACxONwi8')
http://egyg33k.blogspot.com.eg/2016/08/8-malwarebytes-anti-malware.html

Related

Keep N occurrences of a single character in a string in Javascript

Let's say I have this string: "a_b_c_d_restofthestring" and I only want to keep (e.g.) 2 underscores. So,
"a_b_cdrestofthestring"
"abc_d_restofthestring"
Are both valid outputs.
My current implementation is:
let str = "___sdaj___osad$%^&*";
document.getElementById('input').innerText = str;
let u = 0;
str = str.split("").reduce((output, c) => {
if (c == "_") u++;
return u < 2 || c != "_" ? output + c : output;
});
document.getElementById('output').innerText = str;
<div id="input"></div>
<div id="output"></div>
But I'd like to know if there's a better way...
Your code seems to work fine, but here's a one-liner regular expression that replaces all but the last two underscores from the input string.
let input = "___sdaj___osad$%^&*";
let output = input.replace(/_(?=(.*_){2})/g, '');
console.log("input: " + input);
console.log("output: " + output);
This of course is not very generalized, and you'd have to modify the regular expression every time you wanted to say, replace a character other than underscore, or allow 3 occurrences. But if you're okay with that, then this solution has a bit less code to maintain.
Update: Here's an alternate version, that's fully generic and should perform a bit better:
let input = "___sdaj___osad$%^&*";
function replace(input, char = '_', max = 2, replaceWith = '') {
let result = "";
const len = input.length;
for (let i = 0, u = 0; i < len; i++) {
let c = input[i];
result += (c === char && ++u > max) ? replaceWith : c;
}
return result;
}
console.log("input: ", input);
console.log("output: ", replace(input));
See this jsPerf analysis.
You could take a regular expression which looks for an underscore and a counter of the keeping underscores and replace all others.
var string = "a_b_c_d_restofthestring",
result = string.replace(/_/g, (c => _ => c && c-- ? _ : '')(2));
console.log(result);

How can I remove the last emoji of a group of emojis in javascript?

Let's say I have this 3 emojis in a string: πŸ˜€πŸŽƒπŸ‘ͺ
There are not any spaces or any other character except emojis in the string.
How can I remove the last emoji in javascript?
The answer below doesn't use any special package and safely removes the last emoji
function safeEmojiBackspace(str)
{
let initialRealCount = fancyCount(str);
while(str.length > 0 && fancyCount(str) !== initialRealCount - 1)
{
str = str.substring(0,str.length - 1);
}
return str;
}
function fancyCount(str){
const joiner = "\u{200D}";
const split = str.split(joiner);
let count = 0;
for(const s of split){
//removing the variation selectors
const num = Array.from(s.split(/[\ufe00-\ufe0f]/).join("")).length;
count += num;
}
//assuming the joiners are used appropriately
return count / split.length;
}
Sample usage
let str = "somethingπŸ˜€πŸŽƒπŸ‘ͺ";
str = safeEmojiBackspace(str);//"somethingπŸ˜€πŸŽƒ"
You can do this. It will always remove the last emoji.
function removeEmoji() {
var emoStringArray = document.getElementById('emoji').innerHTML;
var lastIndex = emoStringArray.lastIndexOf(" ");
var stripedEmoStringArray = emoStringArray.substring(0, lastIndex);
document.getElementById('emoji').innerHTML = stripedEmoStringArray;
}
<p id="emoji">
πŸ˜€ πŸŽƒ πŸ‘ͺ
</p>
<button onclick="removeEmoji()">Remove</button>
I hope this is what you want.
var emoString = "πŸ˜€ πŸŽƒ πŸ‘ͺ";
emoString = emoString.slice(0, -2);
However, this would work only if you have 3 emojis in total. Hence to achieve a generalised solution, you can use the underscore functions split() and javascript function join() :
var emoString = "πŸ˜€ πŸŽƒ πŸ‘ͺ";
emoString = _.rest(emoString.split(' ')).join(' ')
Hope this will solve your issue.
Ok, here is how I solved it:
function deleteEmoji(emojiStr) {
let emojisArray = emojiStr.match(/([\uD800-\uDBFF][\uDC00-\uDFFF])/g);
emojisArray = emojisArray.splice(0, emojisArray.length - 1);
return emojisArray.join("");
}
let emojitext = "πŸ˜€πŸŽƒπŸ‘ͺ";
console.log(deleteEmoji(emojitext));
I was actually surprised that unicode in this day an age is still not fully supported in browsers. I assume a lot of this is down to windows and it's version of UTF-16.
The OP I believe has found his own solution to the original problem, but I thought there has to be a more generic solution to surrogate pair unicode characters.
Anyway, so my solution is convert the text into a UTF-32 array, these can then be manipulated must easier, using slice etc.
After you have done what you want to the array, just convert back.
Below is an example.
Some of the code I got from -> Is it possible to convert a string containing "high" unicode chars to an array consisting of dec values derived from utf-32 ("real") codes?
and http://speakingjs.com/es5/ch24.html
function decodeUnicode(str) {
const r = [];
let i = 0;
while(i < str.length) {
let chr = str.charCodeAt(i++);
if(chr >= 0xD800 && chr <= 0xDBFF) {
var low = str.charCodeAt(i++);
r.push(0x10000 +
((chr - 0xD800) << 10) | (low - 0xDC00));
} else {
r.push(chr);
}
}
return r;
}
function toUTF16(codePoint) {
const TEN_BITS = parseInt('1111111111', 2);
if (codePoint <= 0xFFFF) { return codePoint; }
codePoint -= 0x10000;
const leadingSurrogate = 0xD800 | (codePoint >> 10);
const trailingSurrogate = 0xDC00 | (codePoint & TEN_BITS);
return String.fromCharCode(leadingSurrogate) +
String.fromCharCode(trailingSurrogate);
}
function encodeUnicode(data) {
return data.reduce((a, v) => {
a += toUTF16(v);
return a;
},"");
}
var unicode = decodeUnicode("πŸ˜€πŸŽƒπŸ‘ͺ");
for (let l = 0; l < unicode.length; l ++)
console.log(encodeUnicode(
unicode.slice(0, l ? -l : unicode.length)));
console.log("pick some random ones");
let str = "";
for (let l = 0; l < 20; l ++) {
let rnd = Math.trunc(Math.random()*unicode.length);
str += encodeUnicode(unicode.slice(rnd,rnd+1));
}
console.log(str);

Regex split on comma don't split on comma between double quotes [duplicate]

I'm looking for [a, b, c, "d, e, f", g, h]to turn into an array of 6 elements: a, b, c, "d,e,f", g, h. I'm trying to do this through Javascript. This is what I have so far:
str = str.split(/,+|"[^"]+"/g);
But right now it's splitting out everything that's in the double-quotes, which is incorrect.
Edit: Okay sorry I worded this question really poorly. I'm being given a string not an array.
var str = 'a, b, c, "d, e, f", g, h';
And I want to turn that into an array using something like the "split" function.
Here's what I would do.
var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
/* will match:
(
".*?" double quotes + anything but double quotes + double quotes
| OR
[^",\s]+ 1 or more characters excl. double quotes, comma or spaces of any kind
)
(?= FOLLOWED BY
\s*, 0 or more empty spaces and a comma
| OR
\s*$ 0 or more empty spaces and nothing else (end of string)
)
*/
arr = arr || [];
// this will prevent JS from throwing an error in
// the below loop when there are no matches
for (var i = 0; i < arr.length; i++) console.log('arr['+i+'] =',arr[i]);
regex: /,(?=(?:(?:[^"]*"){2})*[^"]*$)/
const input_line = '"2C95699FFC68","201 S BOULEVARDRICHMOND, VA 23220","8299600062754882","2018-09-23"'
let my_split = input_line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/)[4]
Output:
my_split[0]: "2C95699FFC68",
my_split[1]: "201 S BOULEVARDRICHMOND, VA 23220",
my_split[2]: "8299600062754882",
my_split[3]: "2018-09-23"
Reference following link for an explanation: regexr.com/44u6o
Here is a JavaScript function to do it:
function splitCSVButIgnoreCommasInDoublequotes(str) {
//split the str first
//then merge the elments between two double quotes
var delimiter = ',';
var quotes = '"';
var elements = str.split(delimiter);
var newElements = [];
for (var i = 0; i < elements.length; ++i) {
if (elements[i].indexOf(quotes) >= 0) {//the left double quotes is found
var indexOfRightQuotes = -1;
var tmp = elements[i];
//find the right double quotes
for (var j = i + 1; j < elements.length; ++j) {
if (elements[j].indexOf(quotes) >= 0) {
indexOfRightQuotes = j;
break;
}
}
//found the right double quotes
//merge all the elements between double quotes
if (-1 != indexOfRightQuotes) {
for (var j = i + 1; j <= indexOfRightQuotes; ++j) {
tmp = tmp + delimiter + elements[j];
}
newElements.push(tmp);
i = indexOfRightQuotes;
}
else { //right double quotes is not found
newElements.push(elements[i]);
}
}
else {//no left double quotes is found
newElements.push(elements[i]);
}
}
return newElements;
}
Here's a non-regex one that assumes doublequotes will come in pairs:
function splitCsv(str) {
return str.split(',').reduce((accum,curr)=>{
if(accum.isConcatting) {
accum.soFar[accum.soFar.length-1] += ','+curr
} else {
accum.soFar.push(curr)
}
if(curr.split('"').length % 2 == 0) {
accum.isConcatting= !accum.isConcatting
}
return accum;
},{soFar:[],isConcatting:false}).soFar
}
console.log(splitCsv('asdf,"a,d",fdsa'),' should be ',['asdf','"a,d"','fdsa'])
console.log(splitCsv(',asdf,,fds,'),' should be ',['','asdf','','fds',''])
console.log(splitCsv('asdf,"a,,,d",fdsa'),' should be ',['asdf','"a,,,d"','fdsa'])
This works well for me. (I used semicolons so the alert message would show the difference between commas added when turning the array into a string and the actual captured values.)
REGEX
/("[^"]*")|[^;]+/
var str = 'a; b; c; "d; e; f"; g; h; "i"';
var array = str.match(/("[^"]*")|[^;]+/g);
alert(array);
Here's the regex we're using to extract valid arguments from a comma-separated argument list, supporting double-quoted arguments. It works for the outlined edge cases. E.g.
doesn't include quotes in the matches
works with white spaces in matches
works with empty fields
(?<=")[^"]+?(?="(?:\s*?,|\s*?$))|(?<=(?:^|,)\s*?)(?:[^,"\s][^,"]*[^,"\s])|(?:[^,"\s])(?![^"]*?"(?:\s*?,|\s*?$))(?=\s*?(?:,|$))
Proof: https://regex101.com/r/UL8kyy/3/tests (Note: currently only works in Chrome because the regex uses lookbehinds which are only supported in ECMA2018)
According to our guidelines it avoids non-capturing groups and greedy matching.
I'm sure it can be simplified, I'm open to suggestions / additional test cases.
For anyone interested, the first part matches double-quoted, comma-delimited arguments:
(?<=")[^"]+?(?="(?:\s*?,|\s*?$))
And the second part matches comma-delimited arguments by themselves:
(?<=(?:^|,)\s*?)(?:[^,"\s][^,"]*[^,"\s])|(?:[^,"\s])(?![^"]*?"(?:\s*?,|\s*?$))(?=\s*?(?:,|$))
I almost liked the accepted answer, but it didn't parse the space correctly, and/or it left the double quotes untrimmed, so here is my function:
/**
* Splits the given string into components, and returns the components array.
* Each component must be separated by a comma.
* If the component contains one or more comma(s), it must be wrapped with double quotes.
* The double quote must not be used inside components (replace it with a special string like __double__quotes__ for instance, then transform it again into double quotes later...).
*
* https://stackoverflow.com/questions/11456850/split-a-string-by-commas-but-ignore-commas-within-double-quotes-using-javascript
*/
function splitComponentsByComma(str){
var ret = [];
var arr = str.match(/(".*?"|[^",]+)(?=\s*,|\s*$)/g);
for (let i in arr) {
let element = arr[i];
if ('"' === element[0]) {
element = element.substr(1, element.length - 2);
} else {
element = arr[i].trim();
}
ret.push(element);
}
return ret;
}
console.log(splitComponentsByComma('Hello World, b, c, "d, e, f", c')); // [ 'Hello World', 'b', 'c', 'd, e, f', 'c' ]
Parse any CSV or CSV-String code based on TYPESCRIPT
public parseCSV(content:string):any[string]{
return content.split("\n").map(ar=>ar.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(refi=>refi.replace(/[\x00-\x08\x0E-\x1F\x7F-\uFFFF]/g, "").trim()));
}
var str='"abc",jkl,1000,qwerty6000';
parseCSV(str);
output :
[
"abc","jkl","1000","qwerty6000"
]
I know it's a bit long, but here's my take:
var sample="[a, b, c, \"d, e, f\", g, h]";
var inQuotes = false, items = [], currentItem = '';
for(var i = 0; i < sample.length; i++) {
if (sample[i] == '"') {
inQuotes = !inQuotes;
if (!inQuotes) {
if (currentItem.length) items.push(currentItem);
currentItem = '';
}
continue;
}
if ((/^[\"\[\]\,\s]$/gi).test(sample[i]) && !inQuotes) {
if (currentItem.length) items.push(currentItem);
currentItem = '';
continue;
}
currentItem += sample[i];
}
if (currentItem.length) items.push(currentItem);
console.log(items);
As a side note, it will work both with, and without the braces in the start and end.
This takes a csv file one line at a time and spits back an array with commas inside speech marks intact. if there are no speech marks detected it just .split(",")s as normal... could probs replace that second loop with something but it does the job as is
function parseCSVLine(str){
if(str.indexOf("\"")>-1){
var aInputSplit = str.split(",");
var aOutput = [];
var iMatch = 0;
//var adding = 0;
for(var i=0;i<aInputSplit.length;i++){
if(aInputSplit[i].indexOf("\"")>-1){
var sWithCommas = aInputSplit[i];
for(var z=i;z<aInputSplit.length;z++){
if(z !== i && aInputSplit[z].indexOf("\"") === -1){
sWithCommas+= ","+aInputSplit[z];
}else if(z !== i && aInputSplit[z].indexOf("\"") > -1){
sWithCommas+= ","+aInputSplit[z];
sWithCommas.replace(new RegExp("\"", 'g'), "");
aOutput.push(sWithCommas);
i=z;
z=aInputSplit.length+1;
iMatch++;
}
if(z === aInputSplit.length-1){
if(iMatch === 0){
aOutput.push(aInputSplit[z]);
}
iMatch = 0;
}
}
}else{
aOutput.push(aInputSplit[i]);
}
}
return aOutput
}else{
return str.split(",")
}
}
Use the npm library csv-string to parse the strings instead of split: https://www.npmjs.com/package/csv-string
This will handle the empty entries
Something like a stack should do the trick. Here I vaguely use marker boolean as stack (just getting my purpose served with it).
var str = "a,b,c,blah\"d,=,f\"blah,\"g,h,";
var getAttributes = function(str){
var result = [];
var strBuf = '';
var start = 0 ;
var marker = false;
for (var i = 0; i< str.length; i++){
if (str[i] === '"'){
marker = !marker;
}
if (str[i] === ',' && !marker){
result.push(str.substr(start, i - start));
start = i+1;
}
}
if (start <= str.length){
result.push(str.substr(start, i - start));
}
return result;
};
console.log(getAttributes(str));
jsfiddle setting image code output image
The code works if your input string in the format of stringTocompare.
Run the code on https://jsfiddle.net/ to see output for fiddlejs setting.
Please refer to the screenshot.
You can either use split function for the same for the code below it and tweak the code according to you need.
Remove the bold or word with in ** from the code if you dont want to have comma after split attach=attach**+","**+actualString[t+1].
var stringTocompare='"Manufacturer","12345","6001","00",,"Calfe,eto,lin","Calfe,edin","4","20","10","07/01/2018","01/01/2006",,,,,,,,"03/31/2004"';
console.log(stringTocompare);
var actualString=stringTocompare.split(',');
console.log("Before");
for(var i=0;i<actualString.length;i++){
console.log(actualString[i]);
}
//var actualString=stringTocompare.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
for(var i=0;i<actualString.length;i++){
var flag=0;
var x=actualString[i];
if(x!==null)
{
if(x[0]=='"' && x[x.length-1]!=='"'){
var p=0;
var t=i;
var b=i;
for(var k=i;k<actualString.length;k++){
var y=actualString[k];
if(y[y.length-1]!=='"'){
p++;
}
if(y[y.length-1]=='"'){
flag=1;
}
if(flag==1)
break;
}
var attach=actualString[t];
for(var s=p;s>0;s--){
attach=attach+","+actualString[t+1];
t++;
}
actualString[i]=attach;
actualString.splice(b+1,p);
}
}
}
console.log("After");
for(var i=0;i<actualString.length;i++){
console.log(actualString[i]);
}
[1]: https://i.stack.imgur.com/3FcxM.png
I solved this with a simple parser.
It simply goes through the string char by char, splitting off a segment when it finds the split_char (e.g. comma), but also has an on/off flag which is switched by finding the encapsulator_char (e.g. quote). It doesn't require the encapsulator to be at the start of the field/segment (a,b","c,d would produce 3 segments, with 'b","c' as the second), but it should work for a well formed CSV with escaped encapsulator chars.
function split_except_within(text, split_char, encapsulator_char, escape_char) {
var start = 0
var encapsulated = false
var fields = []
for (var c = 0; c < text.length; c++) {
var char = text[c]
if (char === split_char && ! encapsulated) {
fields.push(text.substring(start, c))
start = c+1
}
if (char === encapsulator_char && (c === 0 || text[c-1] !== escape_char) )
encapsulated = ! encapsulated
}
fields.push(text.substring(start))
return fields
}
https://jsfiddle.net/7hty8Lvr/1/
const csvSplit = (line) => {
let splitLine = [];
var quotesplit = line.split('"');
var lastindex = quotesplit.length - 1;
// split evens removing outside quotes, push odds
quotesplit.forEach((val, index) => {
if (index % 2 === 0) {
var firstchar = (index == 0) ? 0 : 1;
var trimmed = (index == lastindex)
? val.substring(firstchar)
: val.slice(firstchar, -1);
trimmed.split(",").forEach(v => splitLine.push(v));
} else {
splitLine.push(val);
}
});
return splitLine;
}
this works as long as quotes always come on the outside of values that contain the commas that need to be excluded (i.e. a csv file).
if you have stuff like '1,2,4"2,6",8'
it will not work.
Assuming your string really looks like '[a, b, c, "d, e, f", g, h]', I believe this would be 'an acceptable use case for eval():
myString = 'var myArr ' + myString;
eval(myString);
console.log(myArr); // will now be an array of elements: a, b, c, "d, e, f", g, h
Edit: As Rocket pointed out, strict mode removes eval's ability to inject variables into the local scope, meaning you'd want to do this:
var myArr = eval(myString);
I've had similar issues with this, and I've found no good .net solution so went DIY. NOTE: This was also used to reply to
Splitting comma separated string, ignore commas in quotes, but allow strings with one double quotation
but seems more applicable here (but useful over there)
In my application I'm parsing a csv so my split credential is ",". this method I suppose only works for where you have a single char split argument.
So, I've written a function that ignores commas within double quotes. it does it by converting the input string into a character array and parsing char by char
public static string[] Splitter_IgnoreQuotes(string stringToSplit)
{
char[] CharsOfData = stringToSplit.ToCharArray();
//enter your expected array size here or alloc.
string[] dataArray = new string[37];
int arrayIndex = 0;
bool DoubleQuotesJustSeen = false;
foreach (char theChar in CharsOfData)
{
//did we just see double quotes, and no command? dont split then. you could make ',' a variable for your split parameters I'm working with a csv.
if ((theChar != ',' || DoubleQuotesJustSeen) && theChar != '"')
{
dataArray[arrayIndex] = dataArray[arrayIndex] + theChar;
}
else if (theChar == '"')
{
if (DoubleQuotesJustSeen)
{
DoubleQuotesJustSeen = false;
}
else
{
DoubleQuotesJustSeen = true;
}
}
else if (theChar == ',' && !DoubleQuotesJustSeen)
{
arrayIndex++;
}
}
return dataArray;
}
This function, to my application taste also ignores ("") in any input as these are unneeded and present in my input.

How can I split a string without losing the separator and without regex?

I have a string similar to "<p></p>". Now, I want to split this string, so I have 2 tags. If I do
var arr = "<p></p>".split("><") , I get an array that looks like
["<p", "/p>"]
Is there a simple way to keep the separator in this split? NOT a REGEX (Not a dupe) I want :
["<p>","</p>"]
Since javascript regex doesn't support look behind assertion it's not possible with String#split method. Use String#match method to get the complete string.
var arr = "<p></p>".match(/[\s\S]+?>(?=<|$)/g)
console.log(arr)
Without regex and using split you can do something like this.
var arr = "<p></p>".split('><').map(function(v, i, arr1) {
if (i != 0)
v = '<' + v;
if (i < arr1.length - 1)
v += '>';
return v;
})
// using ternary
var arr1 = "<p></p>".split('><').map(function(v, i, arr1) {
return (i != 0 ? '<' : '') + v + (i < arr1.length - 1 ? '>' : '');
})
console.log(arr);
console.log(arr1);
To do this without a regular expression, you'll need some kind of parser. Inspect every character, build up chunks and store them in an array. You may then want to process the bits, looking for tokens or doing other processing. E.g.
/* Break string into chunks of <...>, </...> and anything in between.
** #param {string} s - string to parse
** #returns {Array} chunks of string
*/
function getChunks(s) {
var parsed = [];
var limit = s.length - 1;
s.split('').reduce(function(buffer, char, i) {
var startTag = char == '<';
var endTag = char == '/';
var closeTag = char == '>';
if (startTag) {
if (buffer.length) {
parsed.push(buffer);
}
buffer = char;
} else if (endTag) {
buffer += char;
} else if (closeTag) {
parsed.push(buffer + char)
buffer = '';
} else {
buffer += char;
}
if (i == limit && buffer.length) {
parsed.push(buffer);
}
return buffer;
}, '');
return parsed;
}
['<p></p>',
'<div>More complex</div>',
'<span>broken tag</sp'
].forEach(function(s){
console.log(s + ' => [' + getChunks(s) + ']')
});
Note that this is very simple and just looks for <...> and </...> where ... can be anything.

Need Help in Converting Code from JS to C#

Here is the Js Code:
n = o.length,
i = "";
for (e = 0; n > e; ++e) e % 3 === 0 && (i += o.substring(e, e + 1));
and C# Code is
int n = newTemp.Length;
string final = "";
for (int e = 0; n > e; ++e)
{
if( e%3==0 )
{
final += newTemp.Substring(e, e + 1);
}
}
but code of C# not giving the same result as JS does.
c# substring is different than js substring.
in js:
text.substring(startIndex, endIndex);
more details
in C#:
text.Substring(startIndex, subtextLength);
More Details
The problem with your C# version is that JS substring takes a start index and an end index, where in C# substring takes a start index and a substring length.
Also, for what your code is doing (only taking a single character), it might be better to do something like this:
int length = inputString.Length;
string result= "";
for (int i = 0; i < length; i++)
{
if (i%3 == 0) result += inputString[i];
}
(The changes to variable names and the for loop are just to make things more readable).

Categories

Resources