Skip to content

Commit b76462c

Browse files
committed
記述、例を追加
1 parent 62503c3 commit b76462c

File tree

1 file changed

+40
-2
lines changed

1 file changed

+40
-2
lines changed

reference/cstdlib/mblen.md

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,19 @@ namespace std {
1212
## 概要
1313
マルチバイト文字列の先頭の文字が占めるバイト数を返す。
1414
15+
先頭以外の文字に関するバイト数は計算されない。
16+
1517
この関数は現在のロケールに依存してマルチバイト文字を解釈する。
16-
n は解析に使用する最大バイト数を指定する。
18+
19+
`n`は解析に使用する最大バイト数を指定する。
1720
1821
## 戻り値
1922
- 正常に動作する場合、文字の占めるバイト数を返す。
2023
- `str`が`nullptr`の時、内部状態を初期化し`0`を返す。
2124
- 無効な文字列、または`n`が不足している場合、`-1`を返す。
2225
2326
## 例
27+
### 基本的な使い方
2428
```cpp example
2529
#include <iostream>
2630
#include <cstdlib>
@@ -35,7 +39,41 @@ int main() {
3539
}
3640
```
3741

38-
### 出力例
42+
#### 出力例
3943
```
4044
3
4145
```
46+
47+
### 文字列の文字数を計算する
48+
```cpp example
49+
#include <iostream>
50+
#include <cstdlib>
51+
#include <clocale>
52+
53+
int count_chars_mblen(const char* s) {
54+
std::setlocale(LC_ALL, "ja_JP.UTF-8");
55+
int count = 0;
56+
size_t i = 0;
57+
while (s[i] != '\0') {
58+
int len = std::mblen(&s[i], MB_CUR_MAX);
59+
if (len < 0) {
60+
len = 1;
61+
}
62+
i += len;
63+
count++;
64+
}
65+
return count;
66+
}
67+
68+
int main() {
69+
const char* str = "こんにちは世界";
70+
std::cout << "文字列: " << str << "\n";
71+
std::cout << "文字数: " << count_chars_mblen(str) << "\n";
72+
}
73+
```
74+
75+
#### 出力例
76+
```
77+
文字列: こんにちは世界
78+
文字数: 7
79+
```

0 commit comments

Comments
 (0)