WeixiangYan/CodeTransOcean huggingface dataset:
Task: Determine if a string has all the same characters








VB: Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
    arr = Array("", "   ", "2", "333", ".55", "tttTTT", "4444 444k", "111111112", " 123")
    For i = LBound(arr) To UBound(arr)
        If SameCharacters(arr(i), respons) Then
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " All characters are the same."
        Else
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " is different at position " & respons & ", character = 
        End If
    Next
End Sub
Function SameCharacters(sTxt, resp As Integer, Optional LowerUpper As Boolean = False) As Boolean
Dim A As String, B As String, i As Integer, temp As Integer
    If Len(sTxt) > 1 Then
        If LowerUpper Then
            SameCharacters = UCase(sTxt) = String$(Len(sTxt), UCase(Left$(sTxt, 1)))
        Else
            SameCharacters = sTxt = String$(Len(sTxt), Left$(sTxt, 1))
        End If
        If Not SameCharacters Then resp = InStr(sTxt, Left$(Replace(sTxt, Left$(sTxt, 1), vbNullString), 1))
    Else
        SameCharacters = True
    End If
End Function




Ada: with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Are_Same is
   procedure All_Chars_Are_Same (S : in String) is
      First_Diff : Natural := 0;
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First + 1 .. S'Last loop
         if S(I) /= S(S'First) then
            First_Diff := I;
            exit;
         end if;
      end loop;
      if First_Diff = 0 then
         Put_Line (" All characters are the same.");
      else
         Put (" First difference at position" & First_Diff'Image &
              ", character = '" & S(First_Diff) &
              "', hex = ");
         Put (Character'Pos (S(First_Diff)), Width => 0, Base => 16);
         New_Line;
      end if;
   end All_Chars_Are_Same;
begin
   All_Chars_Are_Same ("");
   All_Chars_Are_Same ("   ");
   All_Chars_Are_Same ("2");
   All_Chars_Are_Same ("333");
   All_Chars_Are_Same (".55");
   All_Chars_Are_Same ("tttTTT");
   All_Chars_Are_Same ("4444 444k");
end Test_All_Chars_Are_Same;
Task: Determine if a string has all the same characters

C: #include<string.h>
#include<stdio.h>

int main(int argc,char** argv)
{
    int i,len;
    char reference;
    
    if(argc>2){
        printf("Usage : %s <Test String>\n",argv[0]);
        return 0;
    }

    if(argc==1||strlen(argv[1])==1){
        printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1]));
        return 0;
    }

    reference = argv[1][0];
    len = strlen(argv[1]);

    for(i=1;i<len;i++){
        if(argv[1][i]!=reference){
            printf("Input string : \"%s\"\nLength : %d\nFirst different character : \"%c\"(0x%x) at position : %d\n",argv[1],len,argv[1][i],argv[1][i],i+1);
            return 0;
        }
    }

    printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argv[1],len);

    return 0;

}
Task: Determine if a string has all the same characters



C#: using System;

namespace AllSame {
    class Program {
        static void Analyze(string s) {
            Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length);
            if (s.Length > 1) {
                var b = s[0];
                for (int i = 1; i < s.Length; i++) {
                    var c = s[i];
                    if (c != b) {
                        Console.WriteLine("    Not all characters in the string are the same.");
                        Console.WriteLine("    '{0}' (0x{1:X02}) is different at position {2}", c, (int)c, i);
                        return;
                    }
                }

            }
            Console.WriteLine("    All characters in the string are the same.");
        }

        static void Main() {
            var strs = new string[] { "", "   ", "2", "333", ".55", "tttTTT", "4444 444k" };
            foreach (var str in strs) {
                Analyze(str);
            }
        }
    }
}
Task: Determine if a string has all the same characters


C++: #include <iostream>
#include <string>

void all_characters_are_the_same(const std::string& str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    if (len > 0) {
        char ch = str[0];
        for (size_t i = 1; i < len; ++i) {
            if (str[i] != ch) {
                std::cout << "Not all characters are the same.\n";
                std::cout << "Character '" << str[i]
                    << "' (hex " << std::hex << static_cast<unsigned int>(str[i])
                    << ") at position " << std::dec << i + 1
                    << " is not the same as '" << ch << "'.\n\n";
                return;
            }
        }
    }
    std::cout << "All characters are the same.\n\n";
}

int main() {
    all_characters_are_the_same("");
    all_characters_are_the_same("   ");
    all_characters_are_the_same("2");
    all_characters_are_the_same("333");
    all_characters_are_the_same(".55");
    all_characters_are_the_same("tttTTT");
    all_characters_are_the_same("4444 444k");
    return 0;
}
Task: Determine if a string has all the same characters





Java: public class Main{
	public static void main(String[] args){
		String[] tests = {"", "   ", "2", "333", ".55", "tttTTT", "4444 444k"};
		for(String s:tests)
			analyze(s);
	}

	public static void analyze(String s){
		System.out.printf("Examining [%s] which has a length of %d:\n", s, s.length());
		if(s.length() > 1){
			char firstChar = s.charAt(0);
			int lastIndex = s.lastIndexOf(firstChar);
			if(lastIndex != 0){
				System.out.println("\tNot all characters in the string are the same.");
				System.out.printf("\t'%c' (0x%x) is different at position %d\n", firstChar, (int) firstChar, lastIndex);
				return;
			}
		}
		System.out.println("\tAll characters in the string are the same.");
	}
}
Task: Determine if a string has all the same characters







Python: 

from itertools import groupby



def firstDifferingCharLR(s):
    
    def details(xs):
        c = xs[1][0]
        return {
            'char': repr(c),
            'hex': hex(ord(c)),
            'index': s.index(c),
            'total': len(s)
        }
    xs = list(groupby(s))
    return Right(details(xs)) if 1 < len(xs) else (
        Left('Total length ' + str(len(s)) + ' - No character changes.')
    )




def main():
    

    print(fTable('First, if any, points of difference:\n')(repr)(
        either(identity)(
            lambda dct: dct['char'] + ' (' + dct['hex'] +
            ') at character ' + str(1 + dct['index']) +
            ' of ' + str(dct['total']) + '.'
        )
    )(firstDifferingCharLR)([
        '',
        '   ',
        '2',
        '333',
        '.55',
        'tttTTT',
        '4444 444'
    ]))





def either(fl):
    
    return lambda fr: lambda e: fl(e['Left']) if (
        None is e['Right']
    ) else fr(e['Right'])



def identity(x):
    
    return x




def fTable(s):
    
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )



def Left(x):
    
    return {'type': 'Either', 'Right': None, 'Left': x}



def Right(x):
    
    return {'type': 'Either', 'Left': None, 'Right': x}



if __name__ == '__main__':
    main()
Task: Determine if a string has all the same characters








VB: Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
    arr = Array("", "   ", "2", "333", ".55", "tttTTT", "4444 444k", "111111112", " 123")
    For i = LBound(arr) To UBound(arr)
        If SameCharacters(arr(i), respons) Then
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " All characters are the same."
        Else
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " is different at position " & respons & ", character = 
        End If
    Next
End Sub
Function SameCharacters(sTxt, resp As Integer, Optional LowerUpper As Boolean = False) As Boolean
Dim A As String, B As String, i As Integer, temp As Integer
    If Len(sTxt) > 1 Then
        If LowerUpper Then
            SameCharacters = UCase(sTxt) = String$(Len(sTxt), UCase(Left$(sTxt, 1)))
        Else
            SameCharacters = sTxt = String$(Len(sTxt), Left$(sTxt, 1))
        End If
        If Not SameCharacters Then resp = InStr(sTxt, Left$(Replace(sTxt, Left$(sTxt, 1), vbNullString), 1))
    Else
        SameCharacters = True
    End If
End Function
Task: Determine if a string has all the same characters




Go: package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 1; i < le; i++ {
            if chars[i] != chars[i-1] {
                fmt.Println("  Not all characters in the string are the same.")
                fmt.Printf("  %q (%#[1]x) is different at position %d.\n\n", chars[i], i+1)
                return
            }
        }
    }
    fmt.Println("  All characters in the string are the same.\n")
}

func main() {
    strings := []string{
        "",
        "   ",
        "2",
        "333",
        ".55",
        "tttTTT",
        "4444 444k",
        "pépé",
        "🐶🐶🐺🐶",
        "🎄🎄🎄🎄",
    }
    for _, s := range strings {
        analyze(s)
    }
}
Task: Determine if a string has all the same characters



C#: using System;

namespace AllSame {
    class Program {
        static void Analyze(string s) {
            Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length);
            if (s.Length > 1) {
                var b = s[0];
                for (int i = 1; i < s.Length; i++) {
                    var c = s[i];
                    if (c != b) {
                        Console.WriteLine("    Not all characters in the string are the same.");
                        Console.WriteLine("    '{0}' (0x{1:X02}) is different at position {2}", c, (int)c, i);
                        return;
                    }
                }

            }
            Console.WriteLine("    All characters in the string are the same.");
        }

        static void Main() {
            var strs = new string[] { "", "   ", "2", "333", ".55", "tttTTT", "4444 444k" };
            foreach (var str in strs) {
                Analyze(str);
            }
        }
    }
}








Fortran: program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify
Task: Determine if a string has all the same characters


C++: #include <iostream>
#include <string>

void all_characters_are_the_same(const std::string& str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    if (len > 0) {
        char ch = str[0];
        for (size_t i = 1; i < len; ++i) {
            if (str[i] != ch) {
                std::cout << "Not all characters are the same.\n";
                std::cout << "Character '" << str[i]
                    << "' (hex " << std::hex << static_cast<unsigned int>(str[i])
                    << ") at position " << std::dec << i + 1
                    << " is not the same as '" << ch << "'.\n\n";
                return;
            }
        }
    }
    std::cout << "All characters are the same.\n\n";
}

int main() {
    all_characters_are_the_same("");
    all_characters_are_the_same("   ");
    all_characters_are_the_same("2");
    all_characters_are_the_same("333");
    all_characters_are_the_same(".55");
    all_characters_are_the_same("tttTTT");
    all_characters_are_the_same("4444 444k");
    return 0;
}









Fortran: program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify
Task: Determine if a string has all the same characters

C: #include<string.h>
#include<stdio.h>

int main(int argc,char** argv)
{
    int i,len;
    char reference;
    
    if(argc>2){
        printf("Usage : %s <Test String>\n",argv[0]);
        return 0;
    }

    if(argc==1||strlen(argv[1])==1){
        printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1]));
        return 0;
    }

    reference = argv[1][0];
    len = strlen(argv[1]);

    for(i=1;i<len;i++){
        if(argv[1][i]!=reference){
            printf("Input string : \"%s\"\nLength : %d\nFirst different character : \"%c\"(0x%x) at position : %d\n",argv[1],len,argv[1][i],argv[1][i],i+1);
            return 0;
        }
    }

    printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argv[1],len);

    return 0;

}










Fortran: program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify
Task: Determine if a string has all the same characters




Go: package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 1; i < le; i++ {
            if chars[i] != chars[i-1] {
                fmt.Println("  Not all characters in the string are the same.")
                fmt.Printf("  %q (%#[1]x) is different at position %d.\n\n", chars[i], i+1)
                return
            }
        }
    }
    fmt.Println("  All characters in the string are the same.\n")
}

func main() {
    strings := []string{
        "",
        "   ",
        "2",
        "333",
        ".55",
        "tttTTT",
        "4444 444k",
        "pépé",
        "🐶🐶🐺🐶",
        "🎄🎄🎄🎄",
    }
    for _, s := range strings {
        analyze(s)
    }
}







Fortran: program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify
Task: Determine if a string has all the same characters





Java: public class Main{
	public static void main(String[] args){
		String[] tests = {"", "   ", "2", "333", ".55", "tttTTT", "4444 444k"};
		for(String s:tests)
			analyze(s);
	}

	public static void analyze(String s){
		System.out.printf("Examining [%s] which has a length of %d:\n", s, s.length());
		if(s.length() > 1){
			char firstChar = s.charAt(0);
			int lastIndex = s.lastIndexOf(firstChar);
			if(lastIndex != 0){
				System.out.println("\tNot all characters in the string are the same.");
				System.out.printf("\t'%c' (0x%x) is different at position %d\n", firstChar, (int) firstChar, lastIndex);
				return;
			}
		}
		System.out.println("\tAll characters in the string are the same.");
	}
}






Fortran: program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify
Task: Determine if a string has all the same characters







Python: 

from itertools import groupby



def firstDifferingCharLR(s):
    
    def details(xs):
        c = xs[1][0]
        return {
            'char': repr(c),
            'hex': hex(ord(c)),
            'index': s.index(c),
            'total': len(s)
        }
    xs = list(groupby(s))
    return Right(details(xs)) if 1 < len(xs) else (
        Left('Total length ' + str(len(s)) + ' - No character changes.')
    )




def main():
    

    print(fTable('First, if any, points of difference:\n')(repr)(
        either(identity)(
            lambda dct: dct['char'] + ' (' + dct['hex'] +
            ') at character ' + str(1 + dct['index']) +
            ' of ' + str(dct['total']) + '.'
        )
    )(firstDifferingCharLR)([
        '',
        '   ',
        '2',
        '333',
        '.55',
        'tttTTT',
        '4444 444'
    ]))





def either(fl):
    
    return lambda fr: lambda e: fl(e['Left']) if (
        None is e['Right']
    ) else fr(e['Right'])



def identity(x):
    
    return x




def fTable(s):
    
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )



def Left(x):
    
    return {'type': 'Either', 'Right': None, 'Left': x}



def Right(x):
    
    return {'type': 'Either', 'Left': None, 'Right': x}



if __name__ == '__main__':
    main()




Fortran: program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify