Is There a JavaScript Strcmp()

Optimum way to compare strings in JavaScript?

You can use the localeCompare() method.

string_a.localeCompare(string_b);

/* Expected Returns:

0: exact match

-1: string_a < string_b

1: string_a > string_b

*/

Further Reading:

  • MDN: String.prototype.localeCompare
  • Stack Overflow - Is there a JavaScript strcmp()?
  • Tutorials Point: JavaScript String - localeCompare() Method

JavaScript equivalent to C strncmp (compare string for length)

You could easily build that function:

function strncmp(str1, str2, n) {
str1 = str1.substring(0, n);
str2 = str2.substring(0, n);
return ( ( str1 == str2 ) ? 0 :
(( str1 > str2 ) ? 1 : -1 ));
}

An alternative to the ternary at the end of the function could be the localeCompare method e.g return str1.localeCompare(str2);

Javascript string comparer function

Perhaps you should check localeCompare function? That's exactly its purpose: compare the strings. )

Ordinal string compare in JavaScript?

As Raymond noted (and explained) in a comment, an "ordinal" non-locale aware compare is as simple as using the various equality operators on strings (just make sure both operands are strings):

"a" > "b" // false 
"b" > "a" // true

To get a little fancy (or don't muck with [[prototype]], the function is the same):

String.prototype.compare = function (a, b) {
return ((a == b ? 0)
? (a > b : 1)
: -1)
}

Then:

"a".compare("b") // -1

Happy coding.

Why IF statement and strcmp always return FALSE - PHP

You are comparing string "India" to a string "<script>document.write('India');</script>". You can see visually that these 2 strings are nowhere equal or identical.

One way to return true would be to check whether that long-script-string containts string "India", not saying that's the best way to achieve what you are doing with it, moreover it's probably a wrong way but still a way:

if (strpos($country, 'India') !== false) {
echo 'The country string has India in it';
}

Another way would be to remove "<script>document.write('" and "');</script>" from variable $country and only then to compare them.
You can do that with str_replace() or preg_replace().

In any case you should compare a clean variable with a string first and only then wrap that variable in <script> tag, so:

<?php
echo $country = "India"; //Return : India

echo strcmp($country, "India");

if($country === "India")
echo "<br>True";
else
echo "<br>False";

$country = "<script>document.write('" . $country . "');</script>";
?>

P.S. Although I don't understand why you even need to put the country name in document.write()?

Ambiguous behaviour of strcmp()

This is your C code:

int x1()
{
char *a = "abcd";
char *b = "efgh";
printf("%d", strcmp(a,b));
}

int x2()
{
printf("%d", strcmp("abcd", "efgh"));
}

And this is the generated assembly output for both functions:

.LC0:
.string "abcd"
.LC1:
.string "efgh"
.LC2:
.string "%d"
x1:
push rbp
mov rbp, rsp
sub rsp, 16
mov QWORD PTR [rbp-8], OFFSET FLAT:.LC0
mov QWORD PTR [rbp-16], OFFSET FLAT:.LC1
mov rdx, QWORD PTR [rbp-16]
mov rax, QWORD PTR [rbp-8]
mov rsi, rdx
mov rdi, rax
call strcmp // the strcmp function is actually called
mov esi, eax
mov edi, OFFSET FLAT:.LC2
mov eax, 0
call printf
nop
leave
ret

x2:
push rbp
mov rbp, rsp
mov esi, -1 // strcmp is never called, the compiler
// knows what the result will be and it just
// uses -1
mov edi, OFFSET FLAT:.LC2
mov eax, 0
call printf
nop
pop rbp
ret

When the compiler sees strcmp("abcd", "efgh") it knows the result beforehand, because it knows that "abcd" comes before "efgh".

But if it sees strcmp(a,b) it does not know and hence generates code that actually calls strcmp.

With another compiler or with different compiler settings things could be different. You really shouldn't care about such details at least at a beginner's level.

strcmp() function only works on first iteration C

The fscanf format string is wrong, it should be:

"%[^,], %[^,], %d\n"

Note the final \n. Without that, the \n (new line) will not be absorbed and the first item of the next string read will start with \n.

Or even better: use this format string:

" %[^,], %[^,], %d"

Note the space at the beginning. With that format string all leading and trailing whitespace, including the newline, will be absorbed.

Furthermore you absolutely need to check if fopen fails, in your case it apparently doesn't, but if the file cannot be opened for some reason, and you do not any checks, the subsequent operations on f wont end well.

So you need at least this:

...
f = fopen("Customers.txt", "r");
if (f == NULL)
{
printf("Can't open file\n");
return 1;
}
...

In JS, can you rely on comparing strings with the and operators?

No, one cannot rely on alphabetical sorting with the >/< operators. The most prominent example of when data will not be sorted properly this way is with a mix of upper and lower case characters.

Other answers are valid in that using localeCompare is the way to go for comparing strings. However, I have found that numbers and mixes of strings and numbers can also be compared effectively this way as well.

x.localeCompare(y, 'kn', { numeric: true })

By utilizing the numeric option localeCompare provides I was able to achieve much more robust sorting, while also avoiding needing branching conditional logical to handle each the string and the number case.

const rows = [  {name: 'Adam', age: 27, rank: 3, thing: 19},  {name: 'Zeek', age: 31, rank: 1, thing: 'wut dis'},  {name: 'Nancy', age: 45, rank: 4, thing: '$dolla'},  {name: 'Gramps', age: 102, rank: 2, thing: 2},]
const compareFn = (x, y) => { const xData = x[this.state.sortBy].toString() const yData = y[this.state.sortBy].toString() if (this.state.sortDirection !== 'DESC') { return xData.localeCompare(yData, 'kn', { numeric: true }) } else { return yData.localeCompare(xData, 'kn', { numeric: true }) }}
this.state = { sortBy: 'name', sortDirection: 'ASC'}rows.sort(compareFn)console.log('---- Sorted by alphabetical name ----')console.log(rows)
this.state = { sortBy: 'age', sortDirection: 'DESC'}rows.sort(compareFn)console.log('---- Sorted by descending age ----')console.log(rows)
this.state = { sortBy: 'thing', sortDirection: 'ASC'}rows.sort(compareFn)console.log('---- Sorted by ascending thing ----')console.log(rows)


Related Topics



Leave a reply



Submit