Example #1
0
	TrimPositions TrimStringT(const STR& input,
		const STR& trim_chars,
		TrimPositions positions,
		STR* output) {
		// Find the edges of leading/trailing whitespace as desired.
		const size_t last_char = input.length() - 1;
		const size_t first_good_char = (positions & TRIM_LEADING) ?
			input.find_first_not_of(trim_chars) : 0;
		const size_t last_good_char = (positions & TRIM_TRAILING) ?
			input.find_last_not_of(trim_chars) : last_char;

		// When the string was all whitespace, report that we stripped off whitespace
		// from whichever position the caller was interested in.  For empty input, we
		// stripped no whitespace, but we still need to clear |output|.
		if (input.empty() ||
			(first_good_char == STR::npos) || (last_good_char == STR::npos)) {
			bool input_was_empty = input.empty();  // in case output == &input
			output->clear();
			return input_was_empty ? TRIM_NONE : positions;
		}

		// Trim the whitespace.
		*output =
			input.substr(first_good_char, last_good_char - first_good_char + 1);

		// Return where we trimmed from.
		return static_cast<TrimPositions>(
			((first_good_char == 0) ? TRIM_NONE : TRIM_LEADING) |
			((last_good_char == last_char) ? TRIM_NONE : TRIM_TRAILING));
	}
Example #2
0
TrimPositions TrimStringT(const STR& input,
                          const typename STR::value_type trim_chars[],
                          TrimPositions positions,
                          STR* output)
{
    // 根据移除选项positions查找两端边界.
    const typename STR::size_type last_char = input.length() - 1;
    const typename STR::size_type first_good_char = (positions&TRIM_LEADING) ?
        input.find_first_not_of(trim_chars) : 0;
    const typename STR::size_type last_good_char = (positions&TRIM_TRAILING) ?
        input.find_last_not_of(trim_chars) : last_char;

    // 当字符串所有字符都是空白, 根据调用传入的positions返回TrimPositions.
    // 对于空输入没有去除任何空白, 但仍需要对output串调用clear.
    if(input.empty() || (first_good_char==STR::npos) || (last_good_char==STR::npos))
    {
        bool input_was_empty = input.empty();
        output->clear();
        return input_was_empty ? TRIM_NONE : positions;
    }

    // 移除空白.
    *output = input.substr(first_good_char, last_good_char-first_good_char+1);

    // 返回两端哪边移除过.
    return static_cast<TrimPositions>(
        ((first_good_char==0)?TRIM_NONE:TRIM_LEADING) |
        ((last_good_char==last_char)?TRIM_NONE:TRIM_TRAILING));
}