C++字符串常用操作方法总结(持续更新)

1 字符串切割

std::vector splitWithStl(std::string str, std::string pattern)
{
	std::vector result;
	char *strc = new char[strlen(str.c_str()) + 1];
	strcpy(strc, str.c_str());
	char *tokenPtr = strtok(strc, pattern.c_str());
	while (tokenPtr != nullptr) 
	{
		result.push_back(tokenPtr);
		tokenPtr = strtok(nullptr, pattern.c_str());
	}
	return result;
}

2 字符串子串

vector sub_str(string str)
{
	vector v_result;
	for (int i = 0; i < str.size(); i++)
	{
		for (int j = i + 1; j < str.size(); j++)
		{
			string subStr = str.substr(i, j - i + 1);
			v_result.push_back(subStr);
		}
	}
	return v_result;
}

3 回文字符串判断

// 法一
bool isPalindromeStr(string str)
{
	for (int i = 0; i < str.size() / 2; ++i)
	{
		if (str[i] != str[str.size() - 1 - i])
		{
			return false;
		}
	}
	return true;
}

// 法二
bool isPalindromeStr_1(string str)
{
	string str_reverse = str;
	reverse(str_reverse.begin(), str_reverse.end());
	if (str_reverse == str)
	{
		return true;
	}
	else
	{
		return false;
	}
}

4

你可能感兴趣的:(C/C++)