task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Logo
Logo
make "memory (array 32 0)   to load_subleq local "i make "i 0 local "line make "line readlist while [or (not empty? :line) (not list? :line)] [ foreach :line [ setitem :i :memory ? make "i sum :i 1 ] make "line readlist ] end   to run_subleq make "ip 0 while [greaterequal? :ip ...
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Lua
Lua
function subleq (prog) local mem, p, A, B, C = {}, 0 for word in prog:gmatch("%S+") do mem[p] = tonumber(word) p = p + 1 end p = 0 repeat A, B, C = mem[p], mem[p + 1], mem[p + 2] if A == -1 then mem[B] = io.read() elseif B == -1 then io...
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#Rust
Rust
  fn is_prime(num: u32) -> bool { match num { x if x < 4 => x > 1, x if x % 2 == 0 => false, x => { let limit = (x as f32).sqrt().ceil() as u32; (3..=limit).step_by(2).all(|a| x % a != 0) } } }   fn primes_by_diffs(primes: &[u32], diffs: &[u32]) -> Vec<Vec<u32>> {   fn...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Haskell
Haskell
-- We define the functions to return an empty string if the argument is too -- short for the particular operation.   remFirst, remLast, remBoth :: String -> String   remFirst "" = "" remFirst cs = tail cs   remLast "" = "" remLast cs = init cs   remBoth (c:cs) = remLast cs remBoth _ = ""   main :: IO () main = do ...
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Ruby
Ruby
# SubRandom is a subtractive random number generator which generates # the same sequences as Bentley's generator, as used in xpat2. class SubRandom # The original seed of this generator. attr_reader :seed   # Creates a SubRandom generator with the given _seed_. # The _seed_ must be an integer from 0 to 999_999_...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#JavaScript
JavaScript
var array = [1, 2, 3, 4, 5], sum = 0, prod = 1, i; for (i = 0; i < array.length; i += 1) { sum += array[i]; prod *= array[i]; } alert(sum + ' ' + prod);
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 3.141592653589793   Function sumSeries (n As UInteger) As Double If n = 0 Then Return 0 Dim sum As Double = 0 For k As Integer = 1 To n sum += 1.0/(k * k) Next Return sum End Function   Print "s(1000) = "; sumSeries(1000) Print "zeta(2) = "; Pi * pi / 6 Print Print...
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Liberty_BASIC
Liberty BASIC
string1$ = "apples, pears # and bananas" string2$ = "pears;, " + chr$(34) + "apples ; " + chr$(34) + " an;d bananas" commentMarker$ = "; #" Print parse$(string2$, commentMarker$) End   Function parse$(string$, commentMarker$) For i = 1 To Len(string$) charIn$ = Mid$(string$, i, 1) If charIn$ = Chr$(...
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#Phix
Phix
with javascript_semantics constant test = """ /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { a = /* inline comment */ b + c ; } /*/ <-- tricky comments */ /** * Another comment. */ function something() { } """ func...
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#D
D
void main() { import std.stdio, std.string;   "Mary had a %s lamb.".format("little").writeln; "Mary had a %2$s %1$s lamb.".format("little", "white").writeln; }
http://rosettacode.org/wiki/Sum_to_100
Sum to 100
Task Find solutions to the   sum to one hundred   puzzle. Add (insert) the mathematical operators     +   or   -     (plus or minus)   before any of the digits in the decimal numeric string   123456789   such that the resulting mathematical expression adds up to a particular sum   (in this iconic case,   ...
#zkl
zkl
var all = // ( (1,12,123...-1,-12,...), (2,23,...) ...) (9).pump(List,fcn(n){ split("123456789"[n,*]) }) // 45 .apply(fcn(ns){ ns.extend(ns.copy().apply('*(-1))) }); // 90 fcn calcAllSums{ // calculate all 6572 sums (1715 unique) fcn(n,sum,soFar,r){ if(n==9) return(); foreach b in (all[n]){...
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Draco
Draco
\util.g   proc nonrec stripchars(*char str, chars, outbuf) *char: channel input text ch_in; channel output text ch_out; [2]char cur = ('\e', '\e');   open(ch_in, str); open(ch_out, outbuf); while read(ch_in; cur[0]) do if CharsIndex(chars, &cur[0]) = -1 then write(ch_out; cur...
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#EchoLisp
EchoLisp
  ;; using regexp /[chars]/g   (define (strip-chars string chars) (string-replace string (string-append "/[" chars "]/g") ""))   (strip-chars "She was a soul stripper. She took my heart!" "aei") → "Sh ws soul strppr. Sh took my hrt!"  
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lambdatalk
Lambdatalk
  {def str World} -> str   Hello, {str} -> Hello, World  
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lasso
Lasso
local(x = ', World!') #x->merge(1,'Hello') #x // Hello, World!
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <sstream> #include <string>   template <typename T> void demo_compare(const T &a, const T &b, const std::string &semantically) { std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") << "exactly " << semantically << " equal." << std::en...
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Befunge
Befunge
"ATEBahpla" > : #v_ 25* , @ >48*-v > :: "`"` \"{"\` * | > , v > ^ ^ <
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.23
C#
  class Program { public static void Main (string[] args) { var value = "abcd".StartsWith("ab"); value = "abcd".EndsWith("zn"); //returns false value = "abab".Contains("bb"); //returns false value = "abab".Contains("ab"); //returns true int loc = "abab".IndexOf("bb"); //returns -1 loc = "abab".IndexOf("ab...
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#BASIC
BASIC
INPUT a$ PRINT LEN(a$)
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#jq
jq
def strip_control_codes: explode | map(select(. > 31 and . != 127)) | implode;   def strip_extended_characters: explode | map(select(31 < . and . < 127)) | implode;
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#D
D
import std.stdio;   void main() { string s = "hello"; writeln(s ~ " world"); auto s2 = s ~ " world"; writeln(s2); }
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Lingo
Lingo
on sum35 (n) res = 0 repeat with i = 0 to (n-1) if i mod 3=0 OR i mod 5=0 then res = res + i end if end repeat return res end
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Lua
Lua
function sum_digits(n, base) sum = 0 while n > 0.5 do m = math.floor(n / base) digit = n - m * base sum = sum + digit n = m end return sum end   print(sum_digits(1, 10)) print(sum_digits(1234, 10)) print(sum_digits(0xfe, 16)) print(sum_digits(0xf0e, 16))
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Maxima
Maxima
nums : [3,1,4,1,5,9]; sum(nums[i]^2,i,1,length(nums));
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Groovy
Groovy
//Grape setup to get library @Grab('org.apache.commons:commons-lang3:3.0.1') import static org.apache.commons.lang3.StringUtils.*   def abc = '\r\n\t abc \r\n\t'   def printTest = { println ('|' + it + '|') }   println 'Unstripped\n------------' printTest abc   println '============\n\nStripped\n------------' pri...
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#XPL0
XPL0
proc NumOut(Num); \Output positive integer with commas int Num, Dig, Cnt; [Cnt:= [0]; Num:= Num/10; Dig:= rem(0); Cnt(0):= Cnt(0)+1; if Num then NumOut(Num); Cnt(0):= Cnt(0)-1; ChOut(0, Dig+^0); if rem(Cnt(0)/3)=0 & Cnt(0) then ChOut(0, ^,); ];   func IsPrime(N); \Return 'true' if odd N > 2 is prime int ...
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP const N=1e7;   pw,strong,weak := BI(1),List(),List(); // 32,0991 32,1751 ps:=(3).pump(List,'wrap{ pw.nextPrime().toInt() }).copy(); // rolling window do{ pp,p,pn := ps; if((z:=(pp.toFloat() + pn)/2)){ // 2,3,5 --> 3.5 if(z>p) weak .append(p); e...
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Dyalect
Dyalect
let s = "0123456789" let n = 3 let m = 2 let c = '3' let z = "345"   // A: starting from n characters in and of m length; print(s.Substring(n, m)) // B: starting from n characters in, up to the end of the string; print(s[n..]) // C: whole string minus the last character; print(s[..-1]) // D: starting from a known chara...
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Go
Go
package main   import "fmt"   // sudoku puzzle representation is an 81 character string var puzzle = "" + "394 267 " + " 3 4 " + "5 69 2 " + " 45 9 " + "6 7" + " 7 58 " + " 1 67 8" + " 9 8 " + " 264 735"   func main() { printGrid("puzzle:", puzzle) ...
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[memory, MemoryGet, MemorySet, MemorySubtract] memory = {15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0}; MemoryGet[addr_] := memory[[addr + 1]] MemorySet[addr_, value_] := memory[[addr + 1]] = value MemorySubtract[addr1...
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#Scala
Scala
object SuccessivePrimeDiffs { def main(args: Array[String]): Unit = { val d2 = primesByDiffs(2)(1000000) val d1 = primesByDiffs(1)(1000000) val d22 = primesByDiffs(2, 2)(1000000) val d24 = primesByDiffs(2, 4)(1000000) val d42 = primesByDiffs(4, 2)(1000000) val d642 = primesByDiffs(6, 4, 2)(100...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Icon_and_Unicon
Icon and Unicon
procedure main() write(s := "knight"," --> ", s[2:0]) # drop 1st char write(s := "sock"," --> ", s[1:-1]) # drop last write(s := "brooms"," --> ", s[2:-1]) # drop both end
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Rust
Rust
struct SubtractiveGenerator { /// m in the formula modulo: i32, /// i and j in the formula offsets: (u32, u32), /// r in the formula. It is used as a ring buffer. state: Vec<i32>, /// n in the formula position: usize, }   impl SubtractiveGenerator { fn new(modulo: i32, first_offset: ...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#jq
jq
[4,6,8] | add # => 18
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Frink
Frink
  sum[map[{|k| 1/k^2}, 1 to 1000]]  
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Lua
Lua
comment_symbols = ";#"   s1 = "apples, pears # and bananas" s2 = "apples, pears ; and bananas"   print ( string.match( s1, "[^"..comment_symbols.."]+" ) ) print ( string.match( s2, "[^"..comment_symbols.."]+" ) )
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#PHP
PHP
  function strip_block_comments( $test_string ) { $pattern = "/^.*?(\K\/\*.*?\*\/)|^.*?(\K\/\*.*?^.*\*\/)$/mXus"; return preg_replace( $pattern, '', $test_string ); }   echo "Result: '" . strip_block_comments( " /** * Some comments * longer comments here that we can parse. * * Rahoo */ function subroutine() { ...
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#PicoLisp
PicoLisp
(in "sample.txt" (while (echo "/*") (out "/dev/null" (echo "*/")) ) )
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Delphi
Delphi
program Project1;   uses System.SysUtils;   var Template : string; Marker : string; Description : string; Value : integer; Output : string;   begin // StringReplace can be used if you are definitely using strings // http://docwiki.embarcadero.com/Libraries/XE7/en/System.SysUtils.StringReplace Template...
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Elena
Elena
import extensions; import extensions'text; import system'routines;   public program() { var testString := "She was a soul stripper. She took my heart!"; var removeChars := "aei";   console.printLine(testString.filterBy:(ch => removeChars.indexOf(0, ch) == -1).summarize(new StringWriter())) }
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#LFE
LFE
  > (set s "world") "world" > (++ "hello " s) "hello world"  
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lingo
Lingo
str = "world!" put "Hello " before str put str -- "Hello world!"
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#LiveCode
LiveCode
put "world" into x put "hello" before x put x // hello world
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lua
Lua
  s = "12345678" s = "0" .. s print(s)
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Clipper
Clipper
IF s1 == s2  ? "The strings are equal" ENDIF IF .NOT. (s1 == s2)  ? "The strings are not equal" ENDIF IF s1 > s2  ? "s2 is lexically ordered before than s1" ENDIF IF s1 < s2  ? "s2 is lexically ordered after than s1" ENDIF
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Clojure
Clojure
(= "abc" "def") ; false (= "abc" "abc") ; true   (not= "abc" "def") ; true (not= "abc" "abc") ; false
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Bracmat
Bracmat
"alphaBETA":?s & out$str$(upp$!s \n low$!s)
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Burlesque
Burlesque
  blsq ) "alphaBETA"^^zz\/ZZ "ALPHABETA" "alphabeta"  
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#C.2B.2B
C++
#include <string> using namespace std;   string s1="abcd"; string s2="abab"; string s3="ab"; //Beginning s1.compare(0,s3.size(),s3)==0; //End s1.compare(s1.size()-s3.size(),s3.size(),s3)==0; //Anywhere s1.find(s2)//returns string::npos int loc=s2.find(s3)//returns 0 loc=s2.find(s3,loc+1)//returns 2
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion call :length %1 res echo length of %1 is %res% goto :eof   :length set str=%~1 set cnt=0 :loop if "%str%" equ "" ( set %2=%cnt% goto :eof ) set str=!str:~1! set /a cnt = cnt + 1 goto loop
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#Julia
Julia
  stripc0{T<:String}(a::T) = replace(a, r"[\x00-\x1f\x7f]", "") stripc0x{T<:String}(a::T) = replace(a, r"[^\x20-\x7e]", "")   a = "a\n\tb\u2102d\u2147f"   println("Original String:\n ", a) println("\nWith C0 control characters removed:\n ", stripc0(a)) println("\nWith C0 and extended characters removed:\n ", s...
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#Kotlin
Kotlin
// version 1.1.2   fun String.strip(extendedChars: Boolean = false): String { val sb = StringBuilder() for (c in this) { val i = c.toInt() if (i in 32..126 || (!extendedChars && i >= 128)) sb.append(c) } return sb.toString() }   fun main(args: Array<String>) { println("Originally:") ...
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#DCL
DCL
$ string1 = "hello" $ string2 = string1 + " world" $ show symbol string*
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Delphi
Delphi
program Concat;   {$APPTYPE CONSOLE}   var s1, s2: string; begin s1 := 'Hello'; s2 := s1 + ' literal'; WriteLn(s1); WriteLn(s2); end.
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#LiveCode
LiveCode
function sumUntil n repeat with i = 0 to (n-1) if i mod 3 = 0 or i mod 5 = 0 then add i to m end if end repeat return m end sumUntil   put sumUntil(1000) // 233168
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Maple
Maple
sumDigits := proc( num ) local digits, number_to_string, i; number_to_string := convert( num, string ); digits := [ seq( convert( h, decimal, hex ), h in seq( parse( i ) , i in number_to_string ) ) ]; return add( digits ); end proc: sumDigits( 1234 ); sumDigits( "fe" );
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Total[IntegerDigits[1234]] Total[IntegerDigits[16^^FE, 16]]
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Mercury
Mercury
  :- module sum_of_squares. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list.   main(!IO) :- io.write_int(sum_of_squares([3, 1, 4, 1, 5, 9]), !IO), io.nl(!IO).   :- func sum_of_squares(list(int)) = int.   sum_of_squares(Ns) = list.foldl((f...
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#min
min
((bool) ((dup *) (+) map-reduce) (pop 0) if) :sq-sum   (1 2 3 4 5) sq-sum puts () sq-sum puts
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Haskell
Haskell
import Data.Char (isSpace) import Data.List (dropWhileEnd)   trimLeft :: String -> String trimLeft = dropWhile isSpace   trimRight :: String -> String trimRight = dropWhileEnd isSpace   trim :: String -> String trim = trimLeft . trimRight
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Icon_and_Unicon
Icon and Unicon
procedure main() unp := &cset[1+:32]++' \t'++&cset[127:0] # all 'unprintable' chars s := " Hello, people of earth! " write("Original: '",s,"'") write("leading trim: '",reverse(trim(reverse(s),unp)),"'") write("trailing trim: '",trim(s,unp),"'") write("full trim: '",reverse(trim(rev...
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#E
E
def string := "aardvarks" def n := 4 def m := 4 println(string(n, n + m)) println(string(n)) println(string(0, string.size() - 1)) println({string(def i := string.indexOf1('d'), i + m)}) println({string(def i := string.startOf("ard"), i + m)})
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Golfscript
Golfscript
  'Solution:' ;'2 8 4 3 7 5 1 6 9 0 0 9 2 0 0 0 0 7 0 0 1 0 0 4 0 0 2 0 5 0 0 0 0 8 0 0 0 0 8 0 0 0 9 0 0 0 0 6 0 0 0 0 4 0 9 0 0 1 0 0 5 0 0 8 0 0 0 0 7 6 0 4 4 2 5 6 8 9 7 3 1' {9/[n]*puts}:p; #optional formatting   ~]{:@0?:^~!{@p}*10,@9/^9/=-@^9%>9%-@3/^9%3/>3%3/^27/={+}*-{@^<\+@1^+>+}/1}do  
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#MiniScript
MiniScript
memory = [] step = 3 currentAddress = 0 out = ""   process = function(address) A = memory[address].val B = memory[address + 1].val C = memory[address + 2].val nextAddress = address + step   if A == -1 then memory[B] = input else if B == -1 then globals.out = globals.out + char(me...
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Modula-2
Modula-2
MODULE Subleq; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;   TYPE MEMORY = ARRAY[0..31] OF INTEGER; VAR mem : MEMORY; ip,a,b : INTEGER; ch : CHAR; BEGIN mem := MEMORY{ 15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108,...
http://rosettacode.org/wiki/Successive_prime_differences
Successive prime differences
The series of increasing prime numbers begins: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ... The task applies a filter to the series returning groups of successive primes, (s'primes), that differ from the next by a given value or values. Example 1: Specifying that the difference between s'primes be 2 leads to the groups: ...
#Sidef
Sidef
var limit = 1e6 var primes = limit.primes   say "Groups of successive primes <= #{limit.commify}:"   for diffs in [[2], [1], [2,2], [2,4], [4,2], [6,4,2]] {   var groups = [] primes.each_cons(diffs.len+1, {|*group| if (group.map_cons(2, {|a,b| b-a}) == diffs) { groups << group } ...
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#J
J
}. 'knight' NB. drop first item night }: 'socks' NB. drop last item sock }: }. 'brooms' NB. drop first and last items room
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Java
Java
public class RM_chars { public static void main( String[] args ){ System.out.println( "knight".substring( 1 ) ); System.out.println( "socks".substring( 0, 4 ) ); System.out.println( "brooms".substring( 1, 5 ) ); // first, do this by selecting a specific substring // to exclude the first and la...
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Seed7
Seed7
$ include "seed7_05.s7i";   const integer: MOD is 1000000000;   const type: subtractiveGenerator is new struct var array integer: state is [0 .. 54] times 0; var integer: si is 0; var integer: sj is 24; end struct;   const func integer: subrand (inout subtractiveGenerator: generator) is forward;   const f...
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Sidef
Sidef
class SubRandom(seed, state=[]) {   const mod = 1_000_000_000;   method init { var s = [seed % mod, 1]; 53.times { s.append((s[-2] - s[-1]) % mod); } state = s.range.map {|i| s[(34 + 34*i) % 55] }; range(55, 219).each { self.subrand }; }   method subra...
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Julia
Julia
julia> sum([4,6,8]) 18   julia> +((1:10)...) 55   julia +([1,2,3]...) 6   julia> prod([4,6,8]) 192
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#K
K
sum: {+/}x product: {*/}x a: 1 3 5 7 9 11 13 sum a 49 product a 135135
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#F.C5.8Drmul.C3.A6
Fōrmulæ
# We will compute the sum exactly   # Computing an approximation of a rationnal (giving a string) # Value is truncated toward zero Approx := function(x, d) local neg, a, b, n, m, s; if x < 0 then x := -x; neg := true; else neg := false; fi; a := NumeratorRat(x); b := DenominatorRat(x); n := QuoInt(a, b); ...
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Maple
Maple
> use StringTools in map( Trim@Take, [ "\t\t apples, pears \t# and bananas", " apples, pears ; and bananas \t" ], "#;" ) end; ["apples, pears", "apples, pears"]
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = "apples, pears # and bananas apples, pears ; and bananas"; b = StringReplace[a, RegularExpression["[ ]+[#;].+[\n]"] -> "\n"]; StringReplace[b, RegularExpression["[ ]+[#;].+$"] -> ""] // FullForm
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#MATLAB_.2F_Octave
MATLAB / Octave
function line = stripcomment(line) e = min([find(line=='#',1),find(line==';',1)]); if ~isempty(e) e = e-1; while isspace(line(e)) e = e - 1; end; line = line(1:e); end; end;  
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#PL.2FI
PL/I
/* A program to remove comments from text. */ strip: procedure options (main); /* 8/1/2011 */ declare text character (80) varying; declare (j, k) fixed binary;   on endfile (sysin) stop;   do forever; get edit (text) (L); do until (k = 0); k = index(text, '/*'); ...
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#Prolog
Prolog
    :- system:set_prolog_flag(double_quotes,codes) .   strip_block_comments(INPUTz) :- strip_block_comments(INPUTz,OUTPUTz) , system:format("```~n",[OUTPUTz]) , system:format("~s~n",[OUTPUTz]) , system:format("```~n",[OUTPUTz]) .   strip_block_comments(INPUTz,OUTPUTz) :- prolog:phrase(block(OUTPUTz),INPUTz) .   block([...
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#DWScript
DWScript
PrintLn(Format('Mary had a %s lamb.', ['little']))
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Dyalect
Dyalect
let lamb_size = "little" print("Mary had a \(lamb_size) lamb.")
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#E
E
def adjective := "little" `Mary had a $adjective lamb`
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Elixir
Elixir
str = "She was a soul stripper. She took my heart!" String.replace(str, ~r/[aei]/, "") # => Sh ws soul strppr. Sh took my hrt!
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Erlang
Erlang
4> F = fun(To_stripp, Strip_with) -> lists:filter( fun(C) -> not lists:member(C, Strip_with) end, To_stripp ) end. #Fun<erl_eval.12.111823515> 5> F("She was a soul stripper. She took my heart!", "aei"). "Sh ws soul strppr. Sh took my hrt!"
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#M2000_Interpreter
M2000 Interpreter
  Module PrependString { A$="Hello" A$+=" World" Print A$ } PrependString  
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Maple
Maple
l := " World"; m := cat("Hello", l); n := "Hello"||l; o := `||`("Hello", l);
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a = "any text value"; a = "another string literal" <> a (* using concatenation (no built-in prepend) *)
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Mercury
Mercury
:- module string_prepend. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module string. main(!IO) :- S = "World!\n", io.write_string("Hello " ++ S, !IO).
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#COBOL
COBOL
"hello" = "hello" *> equality "helloo" <> "hello" *> inequality "aello" < "hello" *> lexical ordering
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#ColdFusion
ColdFusion
<cffunction name="CompareString"> <cfargument name="String1" type="string"> <cfargument name="String2" type="string"> <cfset VARIABLES.Result = "" > <cfif ARGUMENTS.String1 LT ARGUMENTS.String2 > <cfset VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is less than '" & ARGUMENTS....
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#C
C
/* Demonstrate toupper and tolower for standard C strings. This does not work for multibyte character sets. */ #include <ctype.h> #include <stdio.h>   /* upper-cases s in place */ void str_toupper(char *s) { while(*s) { *s=toupper(*s); s++; } }     /* lower-cases s in place */ void st...
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Clojure
Clojure
(def evals '((. "abcd" startsWith "ab") (. "abcd" endsWith "zn") (. "abab" contains "bb") (. "abab" contains "ab") (. "abab" indexOf "bb") (let [loc (. "abab" indexOf "ab")] (. "abab" indexOf "ab" (dec loc)))))   user> (for [i evals] [i (eval i)]) ([(. "abcd" startsWith "ab") true]...
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#BBC_BASIC
BBC BASIC
INPUT text$ PRINT LEN(text$)
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#langur
langur
val .str = "()\x15abcd\uFFFF123\uBBBB!@#$%^&*\x01"   writeln "original  : ", .str writeln "without ctrl chars: ", replace(.str, RE/\p{Cc}/, ZLS) writeln "print ASCII only  : ", replace(.str, re/[^ -~]/, ZLS)
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#DWScript
DWScript
var s1 := 'Hello'; var s2 := s1 + ' World';   PrintLn(s1); PrintLn(s2);
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Lua
Lua
  function tri (n) return n * (n + 1) / 2 end   function sum35 (n) n = n - 1 return ( 3 * tri(math.floor(n / 3)) + 5 * tri(math.floor(n / 5)) - 15 * tri(math.floor(n / 15)) ) end   print(sum35(1000)) print(sum35(1e+20))  
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 <-> П1 Сx П2 ИП1 ^ ИП0 / [x] П3 ИП0 * - ИП2 + П2 ИП3 П1 x=0 05 ИП2 С/П
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#MiniScript
MiniScript
sumOfSquares = function(seq) sum = 0 for item in seq sum = sum + item*item end for return sum end function   print sumOfSquares([4, 8, 15, 16, 23, 42]) print sumOfSquares([1, 2, 3, 4, 5]) print sumOfSquares([])
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#.D0.9C.D0.9A-61.2F52
МК-61/52
x^2 + С/П БП 00
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#J
J
require 'strings' NB. the strings library is automatically loaded in versions from J7 on quote dlb ' String with spaces ' NB. delete leading blanks 'String with spaces ' quote dtb ' String with spaces ' NB. delete trailing blanks ' String with spaces' quote dltb ' String...
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#EasyLang
EasyLang
a$ = "2019-05-22 22:54:22" print substr a$ 11 5 print substr a$ 11 -1