home > 写経編 > 柴田望洋『明解C言語 入門編』 > 9. 文字列の基本 >

ForNext

Only Do What Only You Can Do

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

VBScript

JScript

Perl

更新日 : 2010.10.18
sub char_count
{
    ($_) = @_;

    # 全角文字数を数え、全角文字を消去する
    $lz = s/[\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc]//g;
    
    # 半角文字数を数える
    $lh = length($_);

    # 全角・半角の文字数を足して返す
    return $lz + $lh;
}

$n = &char_count("123");
print "文字数('123') = $n \n";

$n = length("123");
print "バイト('123') = $n \n";
L:\>perl lesson_09_072.pl
文字数('123') = 3
バイト('123') = 6

PHP

更新日 : 2010.11.03
<?php
function char_count($value)
{
    return mb_strlen($value, "SJIS");
}

$n = char_count("123");
print "文字数('123') = $n \n";

$n = strlen("123");
print "バイト('123') = $n \n";
?>
L:\>php lesson_09_072.php
文字数('123') = 3
バイト('123') = 6

Python

更新日 : 2010.11.17
# coding: Shift_JIS

n = len("123")
print "バイト('123') = %d" % n

n = len(u"123")
print "文字数('123') = %d" % n
N:\>python lesson_09_072.py
バイト('123') = 6
文字数('123') = 3

Ruby

更新日 : 2010.11.01
def char_count(arg)
    return arg.split(//s).length
end

n = char_count("123")
print "文字数('123') = #{n} \n"

n = "123".length
print "バイト('123') = #{n} \n"
L:\>ruby  l:\lesson_09_072.rb
文字数('123') = 3
バイト('123') = 6

PowerShell

Scala

F#

C

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

unsigned str_length(const char str[])
{
    unsigned len = 0;

    while (str[len])
        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:\>lesson072\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;

procedure main();
var
    str: String;
begin
    str := 'ABC';
    Writeln(Format('length(''%s'') = %d', [str, Length(str)]));
end;

begin
    main;
end.
S:\>lesson072\Project1.exe
length('ABC') = 3

Ada

PL/SQL

T-SQL

関数型

inserted by FC2 system