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/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 |... | #C | C | #include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[100]="my String";
char *cstr="Changed ";
char *dup;
sprintf(str,"%s%s",cstr,(dup=strdup(str)));
free(dup);
printf("%s\n",str);
return 0;
} |
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 |... | #11l | 11l | F compare(a, b)
I a < b {print(‘'#.' is strictly less than '#.'’.format(a, b))}
I a <= b {print(‘'#.' is less than or equal to '#.'’.format(a, b))}
I a > b {print(‘'#.' is strictly greater than '#.'’.format(a, b))}
I a >= b {print(‘'#.' is greater than or equal to '#.'’.format(a, b))}
I a == b {print... |
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... | #11l | 11l | V s = ‘alphaBETA’
print(s.uppercase())
print(s.lowercase()) |
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 |... | #Action.21 | Action! | BYTE FUNC FindS(CHAR ARRAY text,sub BYTE start)
BYTE i,j,found
i=start
WHILE i<=text(0)-sub(0)+1
DO
found=0
FOR j=1 TO sub(0)
DO
IF text(i+j-1)#sub(j) THEN
found=0 EXIT
ELSE
found=1
FI
OD
IF found THEN
RETURN (i)
FI
i==+1
OD
RETURN (0)
BY... |
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 |... | #Ada | Ada |
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
procedure Match_Strings is
S1 : constant String := "abcd";
S2 : constant String := "abab";
S3 : constant String := "ab";
begin
if S1'Length >= S3'Length and then S1 (S1'First..S1'First + S3'Length - 1) = S3 then
... |
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... | #8086_Assembly | 8086 Assembly | ;INPUT: DS:SI = BASE ADDR. OF STRING
;TYPICALLY, MS-DOS USES $ TO TERMINATE STRINGS.
GetStringLength:
xor cx,cx ;this takes fewer bytes to encode than "mov cx,0"
cld ;makes string functions post-inc rather than post-dec.
loop_GetStringLength:
lodsb ;equivalent of "mov al,[ds:si],inc si" exce... |
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 ... | #C | C | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAXBUF 256 /* limit */
#define STR_SZ 100 /* string size */
/* function prototypes */
int ascii (const unsigned char c);
int ascii_ext (const unsigned char c);
unsigned char* strip(unsigned char* str, const size_t n, int ext );
/* check... |
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... | #Action.21 | Action! | PROC Append(CHAR ARRAY text,suffix)
BYTE POINTER srcPtr,dstPtr
BYTE len
len=suffix(0)
IF text(0)+len>255 THEN
len=255-text(0)
FI
IF len THEN
srcPtr=suffix+1
dstPtr=text+text(0)+1
MoveBlock(dstPtr,srcPtr,len)
text(0)==+suffix(0)
FI
RETURN
PROC Concatenate(CHAR ARRAY text,left,right)... |
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... | #ActionScript | ActionScript | package
{
public class Str
{
public static function main():void
{
var s:String = "hello";
trace(s + " literal");
var s2:String = s + " literal";
trace(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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Function sum35 (n As UInteger) As UInteger
If n = 0 Then Return 0
Dim As UInteger i, sum = 0
For i = 1 To n
If (i Mod 3 = 0) OrElse (i Mod 5 = 0) Then sum += i
Next
Return sum
End Function
Print "Sum of positive integers below 1000 divisible by 3 or 5 is : "; sum35(999)
Print
Print ... |
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
| #Frink | Frink | sumDigits[n, base=10] := sum[integerDigits[n, base]] |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
local lst
lst := []
#Construct a simple list and pass it to getsum
every put(lst,seq()\2)
write(getsum(lst))
end
procedure getsum(lst)
local total
total := 0
every total +:= !lst ^ 2
return total
end |
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
| #IDL | IDL | print,total(array^2) |
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... | #Burlesque | Burlesque |
blsq ) " this is a string "t[
"this is a string "
blsq ) " this is a string "t]
" this is a string"
blsq ) " this is a string "tt
"this is a string"
|
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char *rtrim(const char *s)
{
while( isspace(*s) || !isprint(*s) ) ++s;
return strdup(s);
}
char *ltrim(const char *s)
{
char *r = strdup(s);
if (r != NULL)
{
char *fr = r + strlen(s) - 1;
while( (isspace(*fr) || !isprint... |
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... | #Ksh | Ksh |
#!/bin/ksh
# Strong and weak primes
# # Find and display (on one line) the first 36 strong primes.
# # Find and display the count of the strong primes below 1,000,000.
# # Find and display the count of the strong primes below 10,000,000.
# # Find and display (on one line) the first 37 weak primes.
# # Find an... |
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... | #Lua | Lua | -- Return a table of the primes up to n, then one more
function primeList (n)
local function isPrime (x)
for d = 3, math.sqrt(x), 2 do
if x % d == 0 then return false end
end
return true
end
local pTable, j = {2, 3}
for i = 5, n, 2 do
if isPrime(i) then
table.insert(pTable, i)
en... |
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 |... | #BASIC | BASIC | DIM baseString AS STRING, subString AS STRING, findString AS STRING
DIM m AS INTEGER, n AS INTEGER
baseString = "abcdefghijklmnopqrstuvwxyz"
n = 12
m = 5
' starting from n characters in and of m length;
subString = MID$(baseString, n, m)
PRINT subString
' starting from n characters in, up to the end of the string... |
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.
| #Common_Lisp | Common Lisp | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))... |
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... | #CLU | CLU | % Read numbers from a stream
read_nums = iter (s: stream) yields (int)
while true do
c: char := stream$getc(s)
while c~='-' & ~(c>='0' & c<='9') do
c := stream$getc(s)
end
acc: int := 0
neg: bool
if c='-' then
neg := true
c := strea... |
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... | #COBOL | COBOL | identification division.
program-id. subleq-program.
data division.
working-storage section.
01 subleq-source-code.
05 source-string pic x(2000).
01 subleq-virtual-machine.
05 memory-table.
10 memory pic s9999
occurs 500 times.
05 a ... |
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:
... | #Julia | Julia | using Primes
function filterdifferences(deltas, N)
allprimes = primes(N)
differences = map(i -> allprimes[i + 1] - allprimes[i], 1:length(allprimes) - 1)
println("Diff Sequence Count First Last")
for delt in deltas
ret = trues(length(allprimes) - length(delt))
for j... |
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... | #Common_Lisp | Common Lisp | > (defvar *str* "∀Ꮺ✤Л◒")
*STR*
> (subseq *str* 1) ; remove first character
"Ꮺ✤Л◒"
> (subseq *str* 0 (1- (length *str*))) ; remove last character
"∀Ꮺ✤Л"
> (subseq *str* 1 (1- (length *str*))) ; remove first and last character
"Ꮺ✤Л" |
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... | #Julia | Julia | i,j,m,d,seed = 55,24,10^9,34,292929 # parameters
s = Array{Int32}(undef,i); r = similar(s)
s[1:2] = [seed,1] # table initialization
for n = 3:i; (s[n] = s[n-2]-s[n-1]) < 0 && (s[n] += m) end
t = 1; for u=1:i; (global t+=d)>i && (t-=i); r[u]=s[t] end # permutation, r = s[(d*(1:i) .% i).+1]
u,... |
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... | #Kotlin | Kotlin | // version 1.1.51
const val MOD = 1_000_000_000
val state = IntArray(55)
var si = 0
var sj = 0
fun subrandSeed(p: Int) {
var p1 = p
var p2 = 1
state[0] = p1 % MOD
var j = 21
for (i in 1..54) {
if (j >=55) j -= 55
state[j] = p2
p2 = p1 - p2
if (p2 < 0) p2 ... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Ring | Ring |
# Project : Substitution Cipher
plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ciphertext = "ZEBRASCDFGHIJKLMNOPQTUVWXY"
test = "flee at once. we are discovered!"
encrypt = "SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!"
see "Plaintext : " + plaintext + nl
see "Ciphertext : " + ciphertext + nl
see "Test : " + test + nl
see "Encoded... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Ruby | Ruby | Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
Key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"
def encrypt(str) = str.tr(Alphabet, Key)
def decrypt(str) = str.tr(Key, Alphabet)
str = 'All is lost, he thought. Everything is ruined. It’s ten past three.'
p encrypted = encrypt(st... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Scala | Scala | object SubstitutionCipher extends App {
private val key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N" + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
private val text =
""""It was still dark, in the early morning hours of the twenty-second of December
| 1946, on the second floor of the house a... |
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.
| #Fermat | Fermat |
[a]:=[(1,1,2,3,5,8,13)];
!!Sigma<i=1,7>[a[i]];
!!Prod<i=1,7>[a[i]];
|
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.
| #Forth | Forth | : third ( a b c -- a b c a ) 2 pick ;
: reduce ( xt n addr cnt -- n' ) \ where xt ( a b -- n )
cells bounds do i @ third execute cell +loop nip ;
create a 1 , 2 , 3 , 4 , 5 ,
' + 0 a 5 reduce . \ 15
' * 1 a 5 reduce . \ 120 |
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... | #Elixir | Elixir | iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end)
1.6439345666815615 |
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... | #Bracmat | Bracmat | ( " apples, pears # and bananas
oranges, mangos ; and a durian"
: ?text
& :?newText
& ( non-blank
= %@:~(" "|\t|\r|\n)
)
& ( cleanUp
=
. @(!arg:?arg ("#"|";") ?)
& @(rev$!arg:? (!non-blank ?:?arg))
& @(rev$!arg:? (!non-blank ?:?arg))
& !arg {You could write & "[" !arg "]" ... |
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... | #C | C | #include<stdio.h>
int main()
{
char ch, str[100];
int i;
do{
printf("\nEnter the string :");
fgets(str,100,stdin);
for(i=0;str[i]!=00;i++)
{
if(str[i]=='#'||str[i]==';')
{
str[i]=00;
break;
}
}
printf("\nThe modified string is : %s",str);
printf("\nDo you want to repeat (y/n): ");
... |
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... | #Delphi | Delphi |
program Strip_block_comments;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1))... |
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, ... | #Phix | Phix | with javascript_semantics
enum SUB=-1, NOP=0, ADD=1
function evaluate(sequence s)
integer res = 0, tmp = 0, op = ADD
for i=1 to length(s) do
if s[i]=NOP then
tmp = tmp*10+i
else
res += op*tmp
tmp = i
op = s[i]
end if
end for
return re... |
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... | #Applesoft_BASIC | Applesoft BASIC | 100 LET S$ = "SHE WAS A SOUL STRIPPER. SHE TOOK MY HEART!"
110 LET RM$ = "AEI"
120 GOSUB 200STRIPCHARS
130 PRINT SC$
190 END
200 REM
210 REM STRIPCHARS
220 REM
230 LET SC$ = ""
240 LET SL = LEN (S$)
250 IF SL = 0 THEN RETURN
260 FOR SI = 1 TO SL
270 LET SM$ = MID$ (S$,SI,1)
280 FOR SJ = 1 TO LEN (... |
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... | #Arturo | Arturo | stripChars: function [str, chars]->
join select split str => [not? in? & split chars]
print stripChars "She was a soul stripper. She took my heart!" "aei" |
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 |... | #C.23 | C# | using System;
namespace PrependString
{
class Program
{
static void Main(string[] args)
{
string str = "World";
str = "Hello " + str;
Console.WriteLine(str);
Console.ReadKey();
}
}
} |
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 |... | #C.2B.2B | C++ | include <vector>
#include <algorithm>
#include <string>
#include <iostream>
int main( ) {
std::vector<std::string> myStrings { "prepended to" , "my string" } ;
std::string prepended = std::accumulate( myStrings.begin( ) ,
myStrings.end( ) , std::string( "" ) , []( std::string a ,
std::string b ) { retu... |
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 |... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program comparString64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstante... |
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 |... | #Action.21 | Action! | PROC TestEqual(CHAR ARRAY s1,s2)
INT res
PrintF("""%S"" and ""%S"" are equal: ",s1,s2)
IF SCompare(s1,s2)=0 THEN
PrintE("True")
ELSE
PrintE("False")
FI
RETURN
PROC TestInequal(CHAR ARRAY s1,s2)
INT res
PrintF("""%S"" and ""%S"" are inequal: ",s1,s2)
IF SCompare(s1,s2)#0 THEN
PrintE("Tr... |
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... | #360_Assembly | 360 Assembly | UCASE CSECT
USING UCASE,R15
MVC UC,PG
MVC LC,PG
OC UC,=16C' ' or X'40' uppercase
NC LC,=16X'BF' and X'BF' lowercase
XPRNT PG,L'PG print original
XPRNT UC,L'UC print uc
XPRNT LC,L'LC ... |
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... | #4D | 4D | $string:="alphaBETA"
$uppercase:=Uppercase($string)
$lowercase:=Lowercase($string) |
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 |... | #Aime | Aime | text t;
data b;
b = "Bangkok";
t = "Bang";
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0,
b.seek(t) != -1,
b.seek(t) != -1 && b.seek(t) + ~t == ~b);
t = "ok";
o_form("starts with, embeds, ends with \"~\": ~, ~, ~\n", t, b.seek(t) == 0,
b.seek(t) != -1,
... |
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... | #4D | 4D | $length:=Length("Hello, world!") |
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 ... | #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RosettaCode
{
class Program
{
static void Main(string[] args)
{
string test = "string of ☺☻♥♦⌂, may include control characters and other ilk.♫☼§►↔◄";
... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure String_Concatenation is
S1 : constant String := "Hello";
S2 : constant String := S1 & " literal";
begin
Put_Line (S1);
Put_Line (S2);
end String_Concatenation; |
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... | #Aime | Aime | text s, v;
s = "Hello";
o_(s, "\n");
v = s + ", World!";
o_(v, "\n"); |
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.
| #Frink | Frink |
sum999 = sum[select[1 to 999, {|n| n mod 3 == 0 or n mod 5 == 0}]]
sumdiv[n, d] :=
{
m = floor[n/d]
m(m + 1)/2 d
}
sum35big[n] := sumdiv[n, 3] + sumdiv[n, 5] - sumdiv[n, 15]
println["The sum of all the multiples of 3 or 5 below 1000 is $sum999"]
println["The sum of all multiples less than 1e20 is " + su... |
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | // File digit.go
package digit
import (
"math/big"
"strconv"
)
func SumString(n string, base int) (int, error) {
i, ok := new(big.Int).SetString(n, base)
if !ok {
return 0, strconv.ErrSyntax
}
if i.Sign() < 0 {
return 0, strconv.ErrRange
}
if i.BitLen() <= 64 {
return Sum(i.Uint64(), base), nil
}
... |
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
| #Inform_7 | Inform 7 | Sum Of Squares is a room.
To decide which number is the sum of (N - number) and (M - number) (this is summing):
decide on N + M.
To decide which number is (N - number) squared (this is squaring):
decide on N * N.
To decide which number is the sum of squares of (L - list of numbers):
decide on the summing reduc... |
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
| #Io | Io | list(3,1,4,1,5,9) map(squared) sum |
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... | #C.23 | C# | using System;
public class TrimExample
{
public static void Main(String[] args)
{
const string toTrim = " Trim me ";
Console.WriteLine(Wrap(toTrim.TrimStart()));
Console.WriteLine(Wrap(toTrim.TrimEnd()));
Console.WriteLine(Wrap(toTrim.Trim()));
}
private static string... |
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... | #C.2B.2B | C++ | #include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>
int main( ) {
std::string testphrase( " There are unwanted blanks here! " ) ;
std::string lefttrimmed = boost::trim_left_copy( testphrase ) ;
std::string righttrimmed = boost::trim_right_copy( testphrase ) ;
std::cout << "Th... |
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... | #Maple | Maple | isStrong := proc(n::posint) local holder;
holder := false;
if isprime(n) and 1/2*prevprime(n) + 1/2*nextprime(n) < n then
holder := true;
end if;
return holder;
end proc:
isWeak := proc(n::posint) local holder;
holder := false;
if isprime(n) and n < 1/2*prevprime(n) + 1/2*nextprime(n) then
holder := tr... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | p = Prime[Range[PrimePi[10^3]]];
SequenceCases[p, ({a_, b_, c_}) /; (a + c < 2 b) :> b, 36, Overlaps -> True]
SequenceCases[p, ({a_, b_, c_}) /; (a + c > 2 b) :> b, 37, Overlaps -> True]
p = Prime[Range[PrimePi[10^6] + 1]];
Length[Select[Partition[p, 3, 1], #[[3]] + #[[1]] < 2 #[[2]] &]]
Length[Select[Partition[p, 3, 1... |
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 |... | #BQN | BQN | 5↑3↓"Marshmallow"
"shmal"
3↓"Marshmallow"
"shmallow"
¯1↓"Marshmallow"
"Marshmallo"
(⊑∘/'m'⊸=)⊸↓"Marshmallow"
"mallow"
(⊑∘/"sh"⊸⍷)⊸↓"Marshmallow"
"shmallow" |
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 |... | #Bracmat | Bracmat | ( (basestring = "The five boxing wizards jump quickly")
& (n = 10)
& (m = 5)
{ starting from n characters in and of m length: }
& @(!basestring:? [(!n+-1) ?substring [(!n+!m+-1) ?)
& out$!substring
{ starting from n characters in, up to the end of the string: }
& @(!basestring:? [(!n+-1) ?substring)
& out$!subs... |
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.
| #Crystal | Crystal | GRID_SIZE = 9
def isNumberInRow(board, number, row)
board[row].includes?(number)
end
def isNumberInColumn(board, number, column)
board.any?{|row| row[column] == number }
end
def isNumberInBox(board, number, row, column)
localBoxRow = row - row % 3
localBoxColumn = column - column % 3
(localBoxRow...(localBo... |
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... | #Common_Lisp | Common Lisp | (defun run (memory)
(loop for pc = 0 then next-pc
until (minusp pc)
for a = (aref memory pc)
for b = (aref memory (+ pc 1))
for c = (aref memory (+ pc 2))
for next-pc = (cond ((minusp a)
(setf (aref memory b) (char-code (read-char)))
... |
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:
... | #Lua | Lua | function findspds(primelist, diffs)
local results = {}
for i = 1, #primelist-#diffs do
result = {primelist[i]}
for j = 1, #diffs do
if primelist[i+j] - primelist[i+j-1] == diffs[j] then
result[j+1] = primelist[i+j]
else
result = nil
break
end
end
results[#re... |
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... | #D | D | import std.stdio;
void main() {
// strip first character
writeln("knight"[1 .. $]);
// strip last character
writeln("socks"[0 .. $ - 1]);
// strip both first and last characters
writeln("brooms"[1 .. $ - 1]);
} |
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... | #Delphi | Delphi | program TopAndTail;
{$APPTYPE CONSOLE}
const
TEST_STRING = '1234567890';
begin
Writeln(TEST_STRING); // full string
Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING))); // first character removed
Writeln(Copy(TEST_STRING, 1, Length(TEST_STRING) - 1)); // last characte... |
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... | #Lua | Lua | function SubGen(seed)
local n, r, s = 54, {}, { [0]=seed, 1 }
for n = 2,54 do s[n] = (s[n-2] - s[n-1]) % 1e9 end
for n = 0,54 do r[n] = s[(34*(n+1))%55] end
local next = function()
n = (n+1) % 55
r[n] = (r[(n-55)%55] - r[(n-24)%55]) % 1e9
return r[n]
end
for n = 55,219 do next() end
return nex... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Sidef | Sidef | module SubstitutionCipher {
const key = %c"]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"
func encode(String s) {
var r = ""
s.each {|c|
r += key[c.ord - 32]
}
return r
}
func decode(String s) {
... |
http://rosettacode.org/wiki/Substitution_cipher | Substitution cipher | Substitution Cipher Implementation - File Encryption/Decryption
Task
Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt... | #Tcl | Tcl | oo::class create SubCipher {
variable Alphabet
variable Key
variable EncMap
variable DecMap
constructor {{alphabet abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ} {cipherbet ""}} {
set Alphabet $alphabet
if {$cipherbet eq ""} {
my key [my RandomKey]
} else {... |
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.
| #Fortran | Fortran | integer, dimension(10) :: a = (/ (i, i=1, 10) /)
integer :: sresult, presult
sresult = sum(a)
presult = product(a) |
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... | #Emacs_Lisp | Emacs Lisp | (defun series (n)
(when (<= n 0)
(user-error "n must be positive"))
(apply #'+ (mapcar (lambda (k) (/ 1.0 (* k k))) (number-sequence 1 n))))
(format "%.10f" (series 1000)) ;=> "1.6439345667" |
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... | #C.23 | C# |
using System.Text.RegularExpressions;
string RemoveComments(string str, string delimiter)
{
//regular expression to find a character (delimiter) and
// replace it and everything following it with an empty string.
//.Trim() will remove all beginning and ending white ... |
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... | #C.2B.2B | C++ | #include <iostream>
#include <string>
std::string strip_white(const std::string& input)
{
size_t b = input.find_first_not_of(' ');
if (b == std::string::npos) b = 0;
return input.substr(b, input.find_last_not_of(' ') + 1 - b);
}
std::string strip_comments(const std::string& input, const std::string& delimi... |
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... | #F.23 | F# | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|... |
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... | #Factor | Factor |
: strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
|
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 |... | #11l | 11l | V extra = ‘little’
print(‘Mary had a ’extra‘ lamb.’)
print(‘Mary had a #. lamb.’.format(extra))
print(f:‘Mary had a {extra} lamb.’) |
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, ... | #Picat | Picat | main =>
L = "23456789",
gen(L,Str),
Exp = parse_term(['1'|Str]),
Exp =:= 100,
println(['1'|Str]).
gen(L@[_],Str) => Str = L.
gen([D|Ds],Str) ?=> Str = [D|StrR], gen(Ds,StrR). % no operator
gen([D|Ds],Str) ?=> Str = ['+',D|StrR], gen(Ds,StrR). % insert +
gen([D|Ds],Str) => Str = ['-',D|StrR], g... |
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... | #Asymptote | Asymptote | string text = "She was a soul stripper. She took my heart!";
string[][] remove = {{"a",""},{"e",""},{"i",""}};
for(var i : remove)
text = replace(text, remove);
}
write(text); |
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... | #AutoHotkey | AutoHotkey | MsgBox % stripchars("She was a soul stripper. She took my heart!","aei")
StripChars(string, charsToStrip){
Loop Parse, charsToStrip
StringReplace, string, string, % A_LoopField, , All
return string
} |
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 |... | #Clojure | Clojure |
(defn str-prepend [a-string, to-prepend]
(str to-prepend a-string))
|
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 |... | #COBOL | COBOL | identification division.
program-id. prepend.
data division.
working-storage section.
1 str pic x(30) value "World!".
1 binary.
2 len pic 9(4) value 0.
2 scratch pic 9(4) value 0.
procedure division.
begin.
perform rev-sub-str
... |
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 |... | #Ada | Ada | with Ada.Text_IO, Ada.Strings.Equal_Case_Insensitive;
procedure String_Compare is
procedure Print_Comparison (A, B : String) is
begin
Ada.Text_IO.Put_Line
("""" & A & """ and """ & B & """: " &
(if A = B then
"equal, "
elsif Ada.Strings.Equal_Case_Insensitive ... |
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... | #6502_Assembly | 6502 Assembly | .lf case6502.lst
.cr 6502
.tf case6502.obj,ap1
;------------------------------------------------------
; String Case for the 6502 by barrym95838 2013.04.07
; Thanks to sbprojects.com for a very nice assembler!
; The target for this assembly is an Apple II with
; mixed-case output capabilities. Apple IIs like... |
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 |... | #ALGOL_68 | ALGOL 68 | # define some appropriate OPerators #
PRIO STARTSWITH = 5, ENDSWITH = 5;
OP STARTSWITH = (STRING str, prefix)BOOL: # assuming LWB = 1 #
IF UPB str < UPB prefix THEN FALSE ELSE str[:UPB prefix]=prefix FI;
OP ENDSWITH = (STRING str, suffix)BOOL: # assuming LWB = 1 #
IF UPB str < UPB suffix THEN FALSE ELSE str[UPB str... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program stringLength64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstant... |
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 ... | #C.2B.2B | C++ | #include <string>
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/casts.hpp>
#include <ctime>
#include <cstdlib>
using namespace boost::lambda ;
struct MyRandomizer {
char operator( )( ) {
return static_cast<char>( rand( ) % 256 ) ;
}
} ;
std::string de... |
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... | #ALGOL_68 | ALGOL 68 | STRING s := "hello";
print ((s + " literal", new line));
STRING s1 := s + " literal";
print ((s1, new line)) |
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... | #ALGOL-M | ALGOL-M |
begin
comment
The string concatenation operator is ||, and the
default string length is 10 characters unless a
longer length (up to 255) is explicitly declared;
string(20) s1, s2;
s1 := "Hello";
write (s1 || ", world");
s2 := s1 || ", world";
write (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.
| #Go | Go | package main
import "fmt"
func main() {
fmt.Println(s35(1000))
}
func s35(n int) int {
n--
threes := n / 3
fives := n / 5
fifteen := n / 15
threes = 3 * threes * (threes + 1)
fives = 5 * fives * (fives + 1)
fifteen = 15 * fifteen * (fifteen + 1)
n = (threes + fives - fiftee... |
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
| #Go | Go | // File digit.go
package digit
import (
"math/big"
"strconv"
)
func SumString(n string, base int) (int, error) {
i, ok := new(big.Int).SetString(n, base)
if !ok {
return 0, strconv.ErrSyntax
}
if i.Sign() < 0 {
return 0, strconv.ErrRange
}
if i.BitLen() <= 64 {
return Sum(i.Uint64(), base), nil
}
... |
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
| #J | J | ss=: +/ @: *: |
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
| #Java | Java | public class SumSquares
{
public static void main(final String[] args)
{
double sum = 0;
int[] nums = {1,2,3,4,5};
for (int i : nums)
sum += i * i;
System.out.println("The sum of the squares is: " + sum);
}
} |
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... | #Clojure | Clojure |
(use 'clojure.string)
(triml " my string ")
=> "my string "
(trimr " my string ")
=> " my string"
(trim " \t\r\n my string \t\r\n ")
=> "my string"
|
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... | #COBOL | COBOL | DISPLAY "'" FUNCTION TRIM(str, LEADING) "'"
DISPLAY "'" FUNCTION TRIM(str, TRAILING) "'"
DISPLAY "'" FUNCTION TRIM(str) "'" |
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... | #Nim | Nim | import math, strutils
const
M = 10_000_000
N = M + 19 # Maximum value for sieve.
# Fill sieve of Erathosthenes.
var comp: array[2..N, bool] # True means composite; default is prime.
for n in countup(3, sqrt(N.toFloat).int, 2):
if not comp[n]:
for k in countup(n * n, N, 2 * n):
comp[k] = true
... |
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... | #Pascal | Pascal | program WeakPrim;
{$IFNDEF FPC}
{$AppType CONSOLE}
{$ENDIF}
const
PrimeLimit = 1000*1000*1000;//must be >= 2*3;
type
tLimit = 0..(PrimeLimit-1) DIV 2;
tPrimCnt = 0..51*1000*1000;
tWeakStrong = record
strong,
balanced,
weak : NativeUint;
... |
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 |... | #Burlesque | Burlesque |
blsq ) "RosettaCode"5.+
"Roset"
blsq ) "RosettaCode"5.+2.-
"set"
blsq ) "RosettaCode""set"ss
2
blsq ) "RosettaCode"J"set"ss.-
"settaCode"
blsq ) "RosettaCode"~]
"RosettaCod"
blsq ) "RosettaCode"[-
"osettaCode"
|
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 |... | #C | C | /*
* RosettaCode: Substring, C89
*
* In this task display a substring: starting from n characters in and of m
* length; starting from n characters in, up to the end of the string; whole
* string minus last character; starting from a known character within the
* string and of m length; starting from a known substr... |
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.
| #Curry | Curry | -----------------------------------------------------------------------------
--- Solving Su Doku puzzles in Curry with FD constraints
---
--- @author Michael Hanus
--- @version December 2005
-----------------------------------------------------------------------------
import CLPFD
import List
-- Solving a Su Doku ... |
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... | #D | D | import std.stdio;
void main() {
int[] mem = [
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
];
int instructionPointer = 0;
do {
int a = mem[instr... |
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:
... | #Kotlin | Kotlin | private fun sieve(limit: Int): Array<Int> {
val primes = mutableListOf<Int>()
primes.add(2)
val c = BooleanArray(limit + 1) // composite = true
// no need to process even numbers > 2
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) {
break
}
var... |
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... | #Eero | Eero | #import <Foundation/Foundation.h>
int main()
autoreleasepool
s := 'knight'
Log( '%@', s[1 .. s.length-1] ) // strip first character
s = 'socks'
Log( '%@', s[0 .. s.length-2] ) // strip last character
s = 'brooms'
Log( '%@', s[1 .. s.length-2] ) // strip both first and last charac... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | initialize[n_] :=
Module[{buffer},
buffer =
Join[Nest[Flatten@{#, Mod[Subtract @@ #[[-2 ;;]], 10^9]} &, {n, 1},
53][[1 + Mod[34 Range@54, 55]]], {n}];
Nest[nextValue, buffer, 165]]
nextValue[buffer_] :=
Flatten@{Rest@buffer, Mod[Subtract @@ buffer[[{1, 32}]], 10^9]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.