Last active
November 16, 2016 07:57
-
-
Save gocha/ac746e5874c117ff7e6186e49d5ac795 to your computer and use it in GitHub Desktop.
文字列をトリムする (trim a string)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// @file | |
/// 文字列をトリムするサンプル。 | |
/** | |
* 文字列をトリムする。 | |
* @param pchBuffer トリム後文字列を格納するバッファ | |
* @param uiBufferSize トリム後文字列バッファのサイズ | |
* @param pchSource トリム元の文字列 | |
* @param pchTrimChars トリム対象文字集合 (for example " \t\n\v\f\r") | |
* @return 成功なら1、失敗なら0を返す。 | |
* @remarks 入力文字列自身を変更することも可能である。(その場合、バッファサイズのチェックはスキップされる。) | |
* @remarks マルチバイトの安全性は考慮されていない。 | |
*/ | |
int GtcTrim( | |
char *pchBuffer, | |
size_t uiBufferSize, | |
const char *pchSource, | |
const char *pchTrimChars) | |
{ | |
// 引数チェック | |
if (pchBuffer == NULL) { | |
return 1; | |
} | |
if (pchSource == NULL) { | |
return 1; | |
} | |
if (pchTrimChars == NULL) { | |
return 1; | |
} | |
// 最初の語句(非トリム対象文字列)の位置を検索 | |
const char *pchToken = pchSource + strspn(pchSource, pchTrimChars); | |
// 最初の語句の位置をトリム後文字列の開始位置として記憶 | |
const char *pchStart = pchToken; | |
// トリム後文字列の終了位置を末尾まで検索 | |
const char *pchEnd = pchToken; | |
while (*pchToken != '\0') { | |
// 次にトリム対象文字が出現する位置(語句の末尾)を検索 | |
const char *pchTokenEnd = strpbrk(pchToken, pchTrimChars); | |
if (pchTokenEnd == NULL) { | |
// トリム対象文字が出現しない場合、文字列の終端をトリム終了位置として検索終了 | |
pchEnd = pchToken + strlen(pchToken); | |
break; | |
} | |
// 見つかった語句の末尾をトリム終了位置として記憶 | |
pchEnd = pchTokenEnd; | |
// 次の語句の開始位置を取得 | |
pchToken = pchTokenEnd + strspn(pchTokenEnd, pchTrimChars); | |
} | |
// トリム後文字列の長さを取得し、バッファの長さを確認する | |
// (ただし、入力文字列自身を変形する場合は長さを確認しない) | |
size_t uiTrimLength = (size_t)(pchEnd - pchStart); | |
if (pchBuffer != pchSource && uiBufferSize < uiTrimLength + 1) { | |
return 1; | |
} | |
// バッファにトリム後文字列をコピーする | |
memmove(pchBuffer, pchStart, uiTrimLength); | |
pchBuffer[uiTrimLength] = '\0'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment