Reputation: 3852
I have got a method length(list,var) which gives me the length of a list but i want to find the length of a String, anyone with a solution ?
Upvotes: 6
Views: 7632
Reputation: 1
use this :
?- same_length('abhi',Z).
Z=4
if you are trying to make a .pl file for this then use this :
samelen(X ,Y) :- string_length(X,Y).
// ctrl+c & ctrl+b to save this file
//Now write this as query:
samelen(roger,Y).
Y=5
Upvotes: 0
Reputation:
If you would like to go ISO Prolog, then you wouldn't use
the name/2
predicate.
ISO Prolog offers you atom_codes/2
and atom_chars/2
. They offer you the
functionaliy of converting an atom back forth to either a list of codes
or a list of characters. Atoms are the strings of a Prolog system, and
characters are simply atoms of length 1. Here are some example invokations
of the two predicates:
?- atom_codes(ant, L).
L = [97,110,116]
?- atom_codes(X, [97,110,116]).
X = ant
?- atom_chars(ant, X).
X = [a,n,t]
?- atom_chars(X,[a,n,t]).
X = ant
Now you wonder how to determine the length of a string aka atom. One
way to go would be to first determine the codes or characters, and then
compute the length of this list. But ISO also offers an atom_length/2
predicate. It works as follows:
?- atom_length(ant,X).
X = 3
Many Prolog systems provide this set of built-in predicates, namely SWI Prolog, GNU Prolog, Jekejeke Prolog etc.. The available character code range and encoding depends on the Prolog system. Some allow only 8-bit codes, some 16-bit codes and some 32-bit codes.
Also the maximum length of an atom might differ, and sometimes there is an extra string type which is not tabled compared with the atom type which is often. But this extra type is usually not the same as a double quote enclosed string, which is only a shorthand for a character list.
Upvotes: 7
Reputation: 3852
was just playing with it and i gave the predicate as
?- length("hello", R).
R = 5.
surprisingly it worked :)
Upvotes: 0
Reputation: 95315
Since strings are atoms, you can't manipulate them directly to get the length, extract substrings, etc. First you have to convert them to character lists with atom_chars/2
:
atom_chars(StrVar, ListVar), length(ListVar, LengthVar).
Upvotes: 2