文字列操作 比較 検索 置換

比較

strcmp("abc","abc") == 0
strA.compare( strB) == 0
strA == strB
string.Compare( strA, strB) == 0
strA.Equals( strB)
strA == strB
a == b
a == b

検索

// 見つからない場合は basic_string::npos
auto pos = a.find( b);

// Cの場合
// 見つからない場合は NULL
char* ptr = std::strstr( "abc", "bc");

// 一番うしろの検索
auto pos = a.rfind( b);

// std::find_end版
std::string a = "abcabc";
std::string b = "bc";
auto it = std::find_end( a.begin(), a.end(), b.begin(), b.end());
std::cout << std::distance( a.begin(), pos)  << std::endl; // 4
// 見つからなければ a.end() 
// 前から調べる
// 見つからなかった場合は -1
var pos = a.IndexOf( b);
// 後ろから調べる
var pos = a.LastIndexOf( b);
pos = string.find( a, b) -- 見つからなかった場合は nil
// string.Index を使う
// 見つからない場合は -1
pos := strings.Index( "abcabc", "ca")

置換

#include <string>
#include <regex>
// 正規表現で置換
std::string str = "abcabc";
str = std::regex_replace( str, std::regex("abc"), "def");
// str = "defdef"
string str = "abcabc";
str = str.Replace( "abc", "def");
// str = "defdef"
str = "abcabc"
str = string.gsub( str, "abc", "def")
-- str = "efgefg"
str := "abcabc"
str = strings.Replace( str, "abc", "def", -1)
// str == "defdef"
One Comment

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です