Determine if a string is collapsible: Difference between revisions

m
syntax highlighting fixup automation
(add <<<>>>)
m (syntax highlighting fixup automation)
Line 84:
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="11l">F collapse(s)
V cs = ‘’
V last = Char("\0")
Line 108:
print(‘original : length = ’s.len‘, string = <<<’s‘>>>’)
print(‘collapsed : length = ’c.len‘, string = <<<’c‘>>>’)
print()</langsyntaxhighlight>
 
{{out}}
Line 140:
=={{header|8080 Assembly}}==
 
<langsyntaxhighlight lang="8080asm">bdos: equ 5
puts: equ 9
org 100h
Line 240:
db 'and they think it',39,'s hell. $'
str5: db ' '
db ' --- Harry S Truman $'</langsyntaxhighlight>
 
{{out}}
Line 257:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Collapse(CHAR ARRAY in,out)
BYTE i,j
CHAR c
Line 294:
Test("I never give 'em hell, I just tell the truth, and they think it's hell. ")
Test(" --- Harry S Truman ")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Determine_if_a_string_is_collapsible.png Screenshot from Atari 8-bit computer]
Line 315:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Collapsible is
procedure Collapse (S : in String) is
Line 337:
Collapse (" --- Harry S Truman ");
end Test_Collapsible;
</syntaxhighlight>
</lang>
 
{{out}}
Line 352:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# returns a collapsed version of s #
# i.e. s with adjacent duplicate characters removed #
Line 384:
OD
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 402:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight APLlang="apl">task←{
⍝ Collapse a string
collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}
Line 428:
⍝ Collapse each string and display it as specified
↑collapse display¨ strs
}</langsyntaxhighlight>
 
{{out}}
Line 447:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">lines: [
{::}
{:"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln :}
Line 456:
 
loop lines 'line ->
print squeeze line</langsyntaxhighlight>
 
{{out}}
Line 467:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">collapsible_string(str){
for i, ch in StrSplit(str){
if (ch <> prev)
Line 474:
}
return "original string:`t" StrLen(str) " characters`t«««" str "»»»`nresultant string:`t" StrLen(res) " characters`t«««" res "»»»"
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">data := [""
, """If I were two-faced, would I be wearing this one?"" --- Abraham Lincoln "
, "..1111111111111111111111111111111111111111111111111111111111111117777888"
Line 482:
for i, v in data
MsgBox % := collapsible_string(v)
return</langsyntaxhighlight>
Outputs:<pre>-----------------------------------------
original string: 0 characters «««»»»
Line 501:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK
BEGIN {
Line 532:
printf("new: %2d <<<%s>>>\n\n",length(new_str),new_str)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 561:
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="bacon">DATA ""
DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "
DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
Line 581:
NEXT
PRINT ">>> - length: ", found
DONE</langsyntaxhighlight>
{{out}}
<pre><<<>>> - length: 0
Line 600:
=={{header|BASIC}}==
 
<langsyntaxhighlight lang="basic">10 READ N%
20 FOR A% = 1 TO N%
30 READ I$: GOSUB 100
Line 625:
430 DATA "..1111111111111111111111111111111111111111111111111111111111111117777888"
440 DATA "I never give 'em hell, I just tell the truth, and they think it's hell. "
450 DATA " --- Harry S Truman "</langsyntaxhighlight>
 
{{out}}
Line 646:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
// Collapse a string
Line 678:
show("I never give 'em hell, I just tell the truth, and they think it's hell. ")
show(" --- Harry S Truman ")
$)</langsyntaxhighlight>
{{out}}
<pre>0: <<<>>>
Line 698:
The base function is very simple: Keep adjacent unequal characters, make sure first character is always preserved.
 
<langsyntaxhighlight lang="bqn">Collapse←(≠↑1∾1↓≠⟜»)⊸/
 
>{
Line 711:
"I never give 'em hell, I just tell the truth, and they think it's hell. "
" --- Harry S Truman "
⟩</langsyntaxhighlight><syntaxhighlight lang="text">┌─
╵ ┌─
╵ 80 "<<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>"
Line 740:
17 "<<< - Hary S Truman >>>"
┘</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight Bracmatlang="bracmat"> ( colapse
= previous
. str
Line 771:
$ "I never give 'em hell, I just tell the truth, and they think it's hell. "
& testcolapse
$ " --- Harry S Truman "</langsyntaxhighlight>
'''Output'''
<pre>«««»»» 0
Line 787:
Identical implementation as in [[Determine_if_a_string_is_squeezable]], as both tasks are very similar. The Lincoln quote contains backslashes to accommodate the double quotes via the command line. strcmpi is not part of the C Standard Library, thus comment out the definition in the code if testing on a system where it is already included.
 
<syntaxhighlight lang="c">
<lang C>
#include<string.h>
#include<stdlib.h>
Line 958:
return 0;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 1,012:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using static System.Linq.Enumerable;
 
Line 1,037:
static string Collapse(string s) => string.IsNullOrEmpty(s) ? "" :
s[0] + new string(Range(1, s.Length - 1).Where(i => s[i] != s[i - 1]).Select(i => s[i]).ToArray());
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,058:
=={{header|C++}}==
The solution is a straightforward application of the standard library function "unique".
<langsyntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <algorithm>
Line 1,083:
test(" --- Harry S Truman ");
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,104:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn collapse [s]
(let [runs (partition-by identity s)]
Line 1,113:
(str (format "Input: <<<%s>>> (len %d)\n" s (count s))
(format "becomes: <<<%s>>> (len %d)\n" out (count out)))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,130:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Collapse a string
collapse = proc (s: string) returns (string)
out: array[char] := array[char]$[]
Line 1,173:
show(ex)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>0 <<<>>>
Line 1,191:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "strings.coh";
 
Line 1,242:
show(strings[i]);
i := i + 1;
end loop;</langsyntaxhighlight>
 
{{out}}
Line 1,262:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
 
void collapsible(string s) {
Line 1,288:
collapsible(`I never give 'em hell, I just tell the truth, and they think it's hell. `);
collapsible(` --- Harry S Truman `);
}</langsyntaxhighlight>
{{out}}
<pre>old: <<<>>>, length = 0
Line 1,307:
{{libheader| System.SysUtils}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Determine_if_a_string_is_collapsible;
 
Line 1,343:
collapsible(' --- Harry S Truman ');
readln;
end.</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// Collapse a String. Nigel Galloway: June 9th., 2020
//As per the task description a function which 'determines if a character string is collapsible' by testing if any consecutive characters are the same.
Line 1,364:
collapse " --- Harry S Truman "
collapse "withoutConsecutivelyRepeatedCharacters"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,376:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel sbufs sequences strings ;
IN: rosetta-code.string-collapse
 
Line 1,404:
} [ show-collapse ] each ;
 
MAIN: collapse-demo</langsyntaxhighlight>
{{out}}
(Using some extra test cases from the Go entry.)
Line 1,439:
=={{header|FreeBASIC}}==
{{trans|BASIC}}
<langsyntaxhighlight lang="freebasic">Const numCad = 5
Data ""
Data "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
Line 1,469:
Next j
Sleep
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,494:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">collapse[str] := str =~ %s/(.)\1+/$1/g
 
lines = ["",
Line 1,503:
 
for line = lines
println[collapse[line]]</langsyntaxhighlight>
{{out}}
<pre>
Line 1,514:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,553:
fmt.Printf("collapsed: length = %2d, string = «««%s»»»\n\n", clen, cs)
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,586:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class StringCollapsible {
static void main(String[] args) {
for ( String s : [
Line 1,611:
return sb.toString()
}
}</langsyntaxhighlight>
{{out}}
<pre>old: 0 <<<>>>
Line 1,638:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Text.Printf (printf)
import Data.Maybe (catMaybes)
import Control.Monad (guard)
Line 1,659:
main =
mapM_ (\(a, b) -> printf "old: %3d «««%s»»»\nnew: %3d «««%s»»»\n\n" (length a) a (length b) b)
$ ((,) <*> collapse) <$> input</langsyntaxhighlight>
{{out}}
<pre>
Line 1,689:
Note that we can also directly define a predicate, and a rewrite, in terms of ''Data.List group'',
 
<langsyntaxhighlight lang="haskell">import Data.List (group)
 
isCollapsible :: String -> Bool
Line 1,695:
 
collapsed :: String -> String
collapsed = map head . group</langsyntaxhighlight>
 
or, without imports, in terms of pattern matching:
 
<langsyntaxhighlight lang="haskell">isCollapsible :: String -> Bool
isCollapsible [] = False
isCollapsible [_] = False
Line 1,709:
collapsed (h:t@(x:_))
| h == x = collapsed t
| otherwise = h : collapsed t</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,752:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">
// Title: Determine if a string is collapsible
 
Line 1,783:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,813:
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
<lang javaScript>
String.prototype.collapse = function() {
let str = this;
Line 1,835:
console.log(`«««${col}»»» (${col.length})`);
}
</syntaxhighlight>
</lang>
 
{{out}} <pre>
Line 1,852:
=={{header|jq}}==
Here we can use the Unix-like `uniq` function defined on (JSON) arrays to define `collapse` on (JSON) strings:
<langsyntaxhighlight lang="jq"># Input: an array
# Output: a stream
def uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);
 
def collapse: explode | [uniq] | implode; </langsyntaxhighlight>
 
The program for the given task can now be written in three lines:
 
<langsyntaxhighlight lang="jq">def Guillemets: "«««\(.)»»»";
 
"Original: \(Guillemets) has length \(length)",
(collapse | "Collapsed \(Guillemets) has length \(length)")
</syntaxhighlight>
</lang>
 
Using the following invocation on the five "raw" (i.e. unquoted) strings yields the results as shown:
Line 1,870:
jq -Rrf program.jq raw.txt
 
<langsyntaxhighlight lang="sh">Original: «««»»» has length 0
Collapsed «««»»» has length 0
Original: «««"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln »»» has length 72
Line 1,879:
Collapsed «««I never give 'em hel, I just tel the truth, and they think it's hel. »»» has length 69
Original: ««« --- Harry S Truman »»» has length 72
Collapsed ««« - Hary S Truman »»» has length 17</langsyntaxhighlight>
 
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">const teststrings = [
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
Line 1,913:
 
testcollapse(teststrings)
</langsyntaxhighlight>{{out}}
<pre>
«««»»» (length 0)
Line 1,936:
</pre>
==== Condensed version: ====
<langsyntaxhighlight lang="julia">const teststrings = [
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
Line 1,949:
println("«««$s»»» (length $n)\n collapses to:\n«««$t»»» (length $(length(t))).\n")
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">fun collapse(s: String): String {
val cs = StringBuilder()
var last: Char = 0.toChar()
Line 1,982:
println()
}
}</langsyntaxhighlight>
{{out}}
<pre>original : length = 0, string = «««»»»
Line 2,009:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 2,051:
print ${#strings[i]} "${Guillemet[0]}${strings[i]}${Guillemet[1]}"
print ${#str} "${Guillemet[0]}${str}${Guillemet[1]}\n"
done</langsyntaxhighlight>
{{out}}<pre>0 «««»»»
0 «««»»»
Line 2,070:
=={{header|Lua}}==
{{trans|C#}}
<langsyntaxhighlight lang="lua">function collapse(s)
local ns = ""
local last = nil
Line 2,103:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>old: 0 <<<>>>
Line 2,121:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[StringCollapse]
StringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]
strings = {"",
Line 2,135:
,
{s, strings}
]</langsyntaxhighlight>
{{out}}
<pre>«««»»»
Line 2,159:
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">
<lang Matlab>
function r = collapse(s)
ix=find((s(1:end-1)==s(2:end))+1;
Line 2,181:
collapse('║ --- Harry S Truman ║', 'r')
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,213:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE StrCollapse;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
Line 2,257:
Task("I never give 'em hell, I just tell the truth, and they think it's hell. ");
Task(" --- Harry S Truman ");
END StrCollapse.</langsyntaxhighlight>
{{out}}
<pre> 0 <<<>>>
Line 2,281:
* On the Interface Pane, in the Command Center, type "demo" and hit enter.
 
<syntaxhighlight lang="netlogo">
<lang NetLogo>
to-report split [ string ]
;; utility reporter to split a string into a list
Line 2,316:
demo-collapse
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,335:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import unicode, strformat
 
proc collapse(s: string) =
Line 2,362:
 
for s in Strings:
s.collapse()</langsyntaxhighlight>
 
{{out}}
Line 2,393:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use utf8;
Line 2,414:
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
length($_), $_, $_ ne $squish ? 'True' : 'False', length($squish), $squish
}</langsyntaxhighlight>
{{out}}
<pre>Length: 0 <<<>>>
Line 2,457:
If you don't have builtins/punique.e to hand, you may want to take a quick look at squeeze() in
[[https://rosettacode.org/wiki/Determine_if_a_string_is_squeezable#Phix]], but obviously w/o ch.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span>
Line 2,490:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,513:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php"><?php
 
function collapseString($string) {
Line 2,554:
echo 'Collapse : string is not collapsing...', PHP_EOL, PHP_EOL;
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,596:
The <code>COLLAPSE</code> procedure compares bytes and would be fine with any 8-bit input.
 
<langsyntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 2,675:
CALL EXIT;
EOF
</syntaxhighlight>
</lang>
{{out}}
<pre>0 <<<>>>
Line 2,693:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">collapse_( [], [] ).
collapse_( [A], [A] ).
collapse_( [A,A|T], R ) :- collapse_( [A|T], R ).
Line 2,701:
string_chars( Str, Chars ),
collapse_( Chars, Result ),
string_chars( Collapsed, Result ).</langsyntaxhighlight>
{{out}}
<pre>
Line 2,739:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
DataSection
STR1:
Line 2,774:
*p_data+StringByteLength(PeekS(*p_data))+2
Wend
Input()</langsyntaxhighlight>
{{out}}
<pre>Before collapse: «««»»» (length: 0)
Line 2,793:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from itertools import groupby
 
def collapser(txt):
Line 2,815:
this = "Collapsed"
sqz = collapser(txt)
print(f"{this:>14} Size: {len(sqz)} «««{sqz}»»»" )</langsyntaxhighlight>
 
{{out}}
Line 2,848:
and for the missing predicate, foregrounded in the task title, and already forgotten in the listing of tests:
 
<langsyntaxhighlight lang="python">'''Determining if a string is collapsible'''
 
from operator import eq
Line 2,886:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[False, True, True, True, True, True, True, True, True, False]</pre>
Line 2,892:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ false -1 rot
witheach
[ 2dup = iff
Line 2,926:
$ "..1111111111111111111111111111111111111111111111111111111111111117777888" task
$ "I never give 'em hell, I just tell the truth, and they think it's hell. " task
$ " --- Harry S Truman " task</langsyntaxhighlight>
 
{{out}}
Line 2,966:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">collapse_string <- function(string){
str_iterable <- strsplit(string, "")[[1]]
Line 3,008:
}
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,060:
=={{header|Racket}}==
 
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (collapse text)
Line 3,087:
(string-length text) text
(string-length collapsed) collapsed))))
</syntaxhighlight>
</lang>
{{out}}
<pre>Original (size 0): «««»»»
Line 3,122:
Technically, the task is asking for a boolean. "Determine if a string is collapsible" is answerable with True/False, so return a boolean as well.
 
<syntaxhighlight lang="raku" perl6line>map {
my $squish = .comb.squish.join;
printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
Line 3,139:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
STRINGS
</syntaxhighlight>
</lang>
{{out}}
<pre>Length: 0 <<<>>>
Line 3,179:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/
@.= /*define a default for the @. array. */
parse arg x /*obtain optional argument from the CL.*/
Line 3,207:
$= $ || _ /*append the character, it's different.*/
end /*j*/
collapsible= y\==$; return $ /*set boolean to true if collapsible.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 3,234:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 3,261:
 
see "done..." + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,280:
=={{header|Ruby}}==
This is built in since at least a decade under the method name 'squeeze'. squeeze(" ") would only squeeze spaces.
<langsyntaxhighlight lang="ruby">strings = ["",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111111111111111117777888",
Line 3,296:
puts
end
</syntaxhighlight>
</lang>
{{out}}
<pre>«««»»» (size 0)
Line 3,327:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn collapse_string(val: &str) -> String {
let mut output = String::new();
let mut chars = val.chars().peekable();
Line 3,365:
println!();
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,396:
===Pure imperative programming 😃===
 
<langsyntaxhighlight Scalalang="scala">object CollapsibleString {
 
/**Collapse a string (if possible)*/
Line 3,449:
 
 
}</langsyntaxhighlight>
{{out}}
<pre>ORIGINAL : length = 0, string = «««»»»
Line 3,484:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func squeeze(str) {
str.gsub(/(.)\1+/, {|s1| s1 })
}
Line 3,502:
say "«««#{str}»»» (length: #{str.len})"
say "«««#{ssq}»»» (length: #{ssq.len})\n"
}</langsyntaxhighlight>
{{out}}
<pre style="font-size: 80%">
Line 3,535:
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">#(
'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'
'headmistressship'
Line 3,553:
showCR:( eachWord,'(length:',eachWord size,')' );
showCR:( shortened,'(length:',shortened size,')' ).
]</langsyntaxhighlight>
{{out}}
<pre>The better the 4-wheel drive, the further you'll be from help when ya get stuck!(length:80)
Line 3,565:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">let strings = [
"",
#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#,
Line 3,581:
for (original, collapsed) in zip(strings, collapsedStrings) {
print (String(format: "%03d «%@»\n%03d «%@»\n", original.count, original, collapsed.count, collapsed))
}</langsyntaxhighlight>
 
{{out}}
Line 3,615:
=={{header|Tcl}}==
Please note the ;# ' comments, there appears to be a syntax hightlighting bug with RC
<langsyntaxhighlight lang="tcl">set test {
{}
{"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln }
Line 3,634:
puts ----------------------
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,662:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Function Collapse(s As String) As String
Line 3,688:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>old: 0 «««»»»
Line 3,707:
=={{header|VBA}}==
Function :
<langsyntaxhighlight lang="vb">Function Collapse(strIn As String) As String
Dim i As Long, strOut As String
If Len(strIn) > 0 Then
Line 3,718:
End If
Collapse = strOut
End Function</langsyntaxhighlight>
To Call :
<langsyntaxhighlight lang="vb">Sub CallCollapse()
Dim S As String
S = vbNullString
Line 3,737:
Debug.Print "String : <<<" & S & ">>>", "Lenght : " & Len(S)
Debug.Print "Collapsed : <<<" & Collapse(S) & ">>>", "Lenght : " & Len(Collapse(S))
End Sub</langsyntaxhighlight>
{{out}}
<pre>String : <<<>>> Lenght : 0
Line 3,752:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang="vlang">// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
fn collapse(s string) (string, int, int) {
Line 3,787:
println("collapsed: length = ${clen:2}, string = «««$cs»»»\n")
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,822:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
// Returns collapsed string, original and new lengths in
Line 3,853:
System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
System.print("collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
}</langsyntaxhighlight>
 
{{out}}
Line 3,886:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0;
char C, I, J, Last;
 
Line 3,915:
Text(0, "<<<"); Text(0, C); Text(0, ">>> "); IntOut(0, J); CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 3,932:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn collapsible(str){ // no Unicode
sink:=Sink(String);
str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },""); // prime with \0
cstr:=sink.close();
return(str.len()!=cstr.len(), cstr);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">strings:=
0'^
"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
Line 3,956:
_,cstr:=collapsible(s);
println("After: %3d >>>%s<<<\n".fmt(cstr.len(),cstr));
}</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits