Longest string challenge: Difference between revisions
Content deleted Content added
Line 1,315: | Line 1,315: | ||
println lines</lang> |
println lines</lang> |
||
{{out}} |
|||
<pre>ccc |
|||
ddd |
|||
ggg</pre> |
|||
=={{header|Nim}}== |
|||
To compare the length of strings, we could have use the standard function "cmp" but it would have been cheating. We could also have used the trick based on exception catching, but, in Nim, IndexError is considered as a defect and, even if in current version (1.4) IndexError is actually catchable, it would probably not still be the case in future versions. |
|||
So, we have used another way to compare the length of strings, clearly not efficient, but efficiency is not a goal here. |
|||
<lang Nim>import strutils |
|||
const |
|||
# Define int constants instead of an enum to use only ints and strings. |
|||
Shorter = -1 |
|||
SameLength = 0 |
|||
Longer = 1 |
|||
type LengthComparison = range[Shorter..Longer] |
|||
func cmpLength(a, b: string): LengthComparison = |
|||
let a = repeat(' ', a.len) |
|||
let b = repeat(' ', b.len) |
|||
result = if a in b: (if b in a: SameLength else: Shorter) else: Longer |
|||
var longest = "" |
|||
var result = "" |
|||
for line in "longest_string_challenge.txt".lines: |
|||
case cmpLength(line, longest) |
|||
of Shorter: |
|||
discard |
|||
of SameLength: |
|||
result.add '\n' & line |
|||
of Longer: |
|||
longest = line |
|||
result = line |
|||
echo result</lang> |
|||
{{out}} |
{{out}} |
||
<pre>ccc |
<pre>ccc |