home > 写経編 > 柴田望洋『明解C言語 入門編』 > 11. 文字列とポインタ >

ForNext

Only Do What Only You Can Do

084. 文字列の長さを調べる

VBScript

JScript

Perl

PHP

Python

Ruby

PowerShell

Scala

F#

C

更新日 : 2010.10.08
#include <stdio.h>
#include <string.h>

unsigned str_length(const char* str)
{
    size_t len = 0;

    while (*str++)
        len++;

    return len;
}

int main(int argc, char* argv[])
{
    char str[100] = "ABC";

    printf("sizeof(\"%s\") = %u\n", str, (unsigned)sizeof(str));
    printf("strlen(\"%s\") = %u\n", str, strlen(str));
    printf("str_length(\"%s\") = %u\n", str, str_length(str));

    return 0;
}
R:\>lesson084\project1.exe
sizeof("ABC") = 100
strlen("ABC") = 3
str_length("ABC") = 3

C++

C++Builder

VC++

C#

Java

Objective-C

D

VB

VB.NET

Delphi

更新日 : 2010.09.24
program Project1;

{$APPTYPE CONSOLE}

uses
    SysUtils;

function str_length(str:PChar):Integer;
begin
    result := 0;
    while (str^ <> #0) do
    begin
        Inc(str);
        Inc(result);
    end;
end;

procedure main();
const
    str: String                = 'ABC';
    ptr: array[0..255] of Char = '12345';
begin
    Writeln(Format('length(''%s'')       = %d', [str, Length(str)]));
    Writeln(Format('sizeof(''%s'')     = %d', [ptr, SizeOf(ptr)]));
    Writeln(Format('strlen(''%s'')     = %d', [ptr, StrLen(ptr)]));
    Writeln(Format('str_length(''%s'') = %d', [ptr, str_length(ptr)]));
end;

begin
    main;
end.
S:\>lesson084\project1.exe
length('ABC')       = 3
sizeof('12345')     = 256
strlen('12345')     = 5
str_length('12345') = 5

Ada

PL/SQL

T-SQL

関数型

inserted by FC2 system