std::string中の改行コードを好きな文字列に変換します。この関数を利用して統一されていない改行コードを1種類に統一することもできます。
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <string>
/*
改行コードを変換する(string)
"¥r¥n", "¥r", "¥n", "¥n¥r"の4種類に対応しています。
*/
std::string ConvertCRLF
(
std::string strString // 変換対象の文字列
, std::string strCRLF // 改行コードを変換したい文字列("¥n"など)
)
{
std::string strRet;
std::string::iterator ite = strString.begin();
std::string::iterator iteEnd = strString.end();
if (0 < strString.size()) {
unsigned char bNextChar = *ite++;
while (1) {
if ('¥r' == bNextChar) {
// 改行確定
strRet += strCRLF;
// EOF判定
if (ite == iteEnd) {
break;
}
// 1文字取得
bNextChar = *ite++;
if ('¥n' == bNextChar) {
// EOF判定
if (ite == iteEnd) {
break;
}
// 1文字取得
bNextChar = *ite++;
}
}
else if ('¥n' == bNextChar) {
// 改行確定
strRet += strCRLF;
// EOF判定
if (ite == iteEnd) {
break;
}
// 1文字取得
bNextChar = *ite++;
if ('¥r' == bNextChar) {
// EOF判定
if (ite == iteEnd) {
break;
}
// 1文字取得
bNextChar = *ite++;
}
}
else {
// 改行以外
strRet += bNextChar;
// EOF判定
if (ite == iteEnd) {
break;
}
// 1文字取得
bNextChar = *ite++;
}
};
}
return(strRet);
}
/*
stringの改行コードを統一する
*/
int _tmain
(
int argc
, _TCHAR* argv[]
)
{
/*
std::wcoutのロケールを設定
これを設定するだけで、std::wcoutで日本語が表示される
ようになります。
*/
std::wcout.imbue( std::locale( "", std::locale::ctype ) );
// 変換対象の文字列
std::string strText = "1行目¥r¥n2行目¥n3行目¥n¥r4行目¥r";
// 改行コードを変換します。
std::string strResult = ConvertCRLF( strText, "●" );
// 変換結果を表示
std::cout << strResult.c_str() << std::endl;
// 改行コードを変換します。(このようにすると改行コードを"¥n"に統一する事もできます。)
strResult = ConvertCRLF( strText, "¥n" );
// 変換結果を表示
std::cout << strResult.c_str() << std::endl;
// 正常終了
return( 0 );
}
1行目●2行目●3行目●4行目● 1行目 2行目 3行目 4行目