การลบช่องว่างนำหน้าและต่อท้ายออกจากสตริง


92

วิธีลบช่องว่างจากวัตถุสตริงใน C ++
ตัวอย่างเช่นวิธีการลบช่องว่างนำหน้าและต่อท้ายออกจากวัตถุสตริงด้านล่าง

//Original string: "         This is a sample string                    "
//Desired string: "This is a sample string"

เท่าที่ฉันทราบคลาสสตริงไม่มีวิธีใด ๆ ในการลบช่องว่างนำหน้าและต่อท้าย

หากต้องการเพิ่มปัญหาวิธีขยายการจัดรูปแบบนี้เพื่อประมวลผลช่องว่างเพิ่มเติมระหว่างคำของสตริง ตัวอย่างเช่น,

// Original string: "          This       is         a sample   string    " 
// Desired string:  "This is a sample string"  

การใช้วิธีการสตริงที่กล่าวถึงในโซลูชันฉันสามารถคิดว่าจะดำเนินการเหล่านี้ได้ในสองขั้นตอน

  1. ลบช่องว่างนำหน้าและต่อท้าย
  2. ใช้find_first_of, find_last_of, find_first_not_of, find_last_not_of และ substrซ้ำ ๆ ที่ขอบเขตของคำเพื่อให้ได้รูปแบบที่ต้องการ

คำตอบ:


128

นี้เรียกว่าการตัดแต่ง หากคุณสามารถใช้Boostได้ฉันขอแนะนำ

มิฉะนั้นใช้find_first_not_ofเพื่อรับดัชนีของอักขระที่ไม่ใช่ช่องว่างตัวแรกจากนั้นfind_last_not_ofรับดัชนีจากจุดสิ้นสุดที่ไม่ใช่ช่องว่าง ด้วยสิ่งเหล่านี้ใช้substrเพื่อรับสตริงย่อยโดยไม่มีช่องว่างรอบ ๆ

ในการตอบสนองต่อการแก้ไขของคุณฉันไม่ทราบคำศัพท์ แต่ฉันคาดเดาบางอย่างตามบรรทัดของ "ลด" นั่นคือสิ่งที่ฉันเรียกมัน :) (หมายเหตุฉันได้เปลี่ยนช่องว่างเป็นพารามิเตอร์เพื่อความยืดหยุ่น)

#include <iostream>
#include <string>

std::string trim(const std::string& str,
                 const std::string& whitespace = " \t")
{
    const auto strBegin = str.find_first_not_of(whitespace);
    if (strBegin == std::string::npos)
        return ""; // no content

    const auto strEnd = str.find_last_not_of(whitespace);
    const auto strRange = strEnd - strBegin + 1;

    return str.substr(strBegin, strRange);
}

std::string reduce(const std::string& str,
                   const std::string& fill = " ",
                   const std::string& whitespace = " \t")
{
    // trim first
    auto result = trim(str, whitespace);

    // replace sub ranges
    auto beginSpace = result.find_first_of(whitespace);
    while (beginSpace != std::string::npos)
    {
        const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
        const auto range = endSpace - beginSpace;

        result.replace(beginSpace, range, fill);

        const auto newStart = beginSpace + fill.length();
        beginSpace = result.find_first_of(whitespace, newStart);
    }

    return result;
}

int main(void)
{
    const std::string foo = "    too much\t   \tspace\t\t\t  ";
    const std::string bar = "one\ntwo";

    std::cout << "[" << trim(foo) << "]" << std::endl;
    std::cout << "[" << reduce(foo) << "]" << std::endl;
    std::cout << "[" << reduce(foo, "-") << "]" << std::endl;

    std::cout << "[" << trim(bar) << "]" << std::endl;
}

ผลลัพธ์:

[too much               space]  
[too much space]  
[too-much-space]  
[one  
two]  

ฉันคิดว่าคุณหมายถึง 'size_t' และคุณมี off-by-one บนสตริงย่อยควรเป็น substr (beginStr, endStr - beginStr + 1);
goldPseudo

ควรsite_tจะเป็นsize_t? และฉันคิดว่าที่คุณมีความคิดเห็นno whitespaceหมายความว่าสตริงเป็นช่องว่างหรือว่างเปล่า
Fred Larson

ขอบคุณแก้ไขการsize_tพิมพ์ผิดและแก้ไขทีละรายการ แต่ไม่ได้สังเกตว่าความคิดเห็นของฉันถูกกลับด้านขอบคุณ
GManNickG

@GMan โซลูชันที่หรูหรามาก ขอบคุณ.
Ankur

ข้อบกพร่อง: ลองเรียกใช้ "one \ ttwo" ผ่านส่วนตัด () ผลลัพธ์คือสตริงว่าง คุณต้องทดสอบ endStr กับ std :: string :: npos ด้วย
dlchambers

48

ง่ายต่อการลบช่องว่างนำหน้าต่อท้ายและช่องว่างเพิ่มเติมจาก std :: string ในบรรทัดเดียว

value = std::regex_replace(value, std::regex("^ +| +$|( ) +"), "$1");

ลบเฉพาะช่องว่างนำหน้า

value.erase(value.begin(), std::find_if(value.begin(), value.end(), std::bind1st(std::not_equal_to<char>(), ' ')));

หรือ

value = std::regex_replace(value, std::regex("^ +"), "");

ลบเฉพาะช่องว่างต่อท้าย

value.erase(std::find_if(value.rbegin(), value.rend(), std::bind1st(std::not_equal_to<char>(), ' ')).base(), value.end());

หรือ

value = std::regex_replace(value, std::regex(" +$"), "");

ลบเฉพาะช่องว่างเพิ่มเติม

value = regex_replace(value, std::regex(" +"), " ");

3
ทำได้ดีนี่. การให้ข้อมูลเกี่ยวกับสิ่งที่เกิดขึ้นที่นี่จะเป็นประโยชน์เนื่องจากเป็นการยากที่จะเข้าใจรหัสเหล่านี้
Marcin

ใช้ได้เฉพาะใน C ++ 11 เท่านั้น
Martin Pecka

7
ไม่ได้ลบแท็บออก แต่สามารถแก้ไขได้ สิ่งที่แก้ไขไม่ได้คือมันช้ามาก (~ 100 เท่าช้ากว่าคำตอบที่มีsubstrหรือerase)
4LegsDrivenCat

สำหรับการเพิ่มประสิทธิภาพความเร็ว regex ไม่ใช่โซลูชันที่ดีที่สุด แต่สามารถปรับปรุงได้โดยการสร้าง regex เพียงครั้งเดียว
Evgeny Karpov

40

ฉันกำลังใช้ฟังก์ชันเหล่านี้:

// trim from left
inline std::string& ltrim(std::string& s, const char* t = " \t\n\r\f\v")
{
    s.erase(0, s.find_first_not_of(t));
    return s;
}

// trim from right
inline std::string& rtrim(std::string& s, const char* t = " \t\n\r\f\v")
{
    s.erase(s.find_last_not_of(t) + 1);
    return s;
}

// trim from left & right
inline std::string& trim(std::string& s, const char* t = " \t\n\r\f\v")
{
    return ltrim(rtrim(s, t), t);
}

// copying versions

inline std::string ltrim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return ltrim(s, t);
}

inline std::string rtrim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return rtrim(s, t);
}

inline std::string trim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return trim(s, t);
}


9

นี่คือวิธีแก้ปัญหาของฉันสำหรับการลอกช่องว่างนำหน้าและต่อท้าย ...

std::string stripString = "  Plamen     ";
while(!stripString.empty() && std::isspace(*stripString.begin()))
    stripString.erase(stripString.begin());

while(!stripString.empty() && std::isspace(*stripString.rbegin()))
    stripString.erase(stripString.length()-1);

ผลที่ได้คือ "Plamen"


8

นี่คือวิธีที่คุณสามารถทำได้:

std::string & trim(std::string & str)
{
   return ltrim(rtrim(str));
}

และฟังก์ชั่นการสนับสนุนนั้นใช้งานได้ดังนี้

std::string & ltrim(std::string & str)
{
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   
}

std::string & rtrim(std::string & str)
{
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   
}

และเมื่อคุณได้สิ่งเหล่านี้ครบแล้วคุณก็สามารถเขียนสิ่งนี้ได้เช่นกัน:

std::string trim_copy(std::string const & str)
{
   auto s = str;
   return ltrim(rtrim(s));
}

ลองทำตามนี้


7

ตัวอย่างการตัดแต่งช่องว่างนำหน้าและต่อท้ายตามคำแนะนำของจอนฮันสันในการใช้บูสต์ (ลบเฉพาะช่องว่างต่อท้ายและช่องว่างที่รอดำเนินการ):

#include <boost/algorithm/string/trim.hpp>

std::string str = "   t e s t    ";

boost::algorithm::trim ( str );

ผลลัพธ์เป็น "t e s t"

นอกจากนี้ยังมี

  • trim_left ผลลัพธ์ใน "t e s t "
  • trim_right ผลลัพธ์ใน " t e s t"

5
/// strip a string, remove leading and trailing spaces
void strip(const string& in, string& out)
{
    string::const_iterator b = in.begin(), e = in.end();

    // skipping leading spaces
    while (isSpace(*b)){
        ++b;
    }

    if (b != e){
        // skipping trailing spaces
        while (isSpace(*(e-1))){
            --e;
        }
    }

    out.assign(b, e);
}

ในโค้ดด้านบนฟังก์ชัน isSpace () เป็นฟังก์ชันบูลีนที่บอกว่าอักขระเป็นพื้นที่สีขาวหรือไม่คุณสามารถใช้ฟังก์ชันนี้เพื่อสะท้อนความต้องการของคุณหรือเพียงแค่เรียก isspace () จาก "ctype.h" หากคุณต้องการ .


4

ตัวอย่างการตัดแต่งช่องว่างด้านหน้าและด้านหลัง

std::string aString("    This is a string to be trimmed   ");
auto start = aString.find_first_not_of(' ');
auto end = aString.find_last_not_of(' ');
std::string trimmedString;
trimmedString = aString.substr(start, (end - start) + 1);

หรือ

trimmedSring = aString.substr(aString.find_first_not_of(' '), (aString.find_last_not_of(' ') - aString.find_first_not_of(' ')) + 1);

3
ผู้คนไม่ชอบดูโค้ด 10 หน้าเพื่อเรียนรู้วิธีตัดแต่งสตริง
Thinkal VB

2
จะเสียถ้าสตริงมีช่องว่างเท่านั้น
DAG

3

การใช้ไลบรารีมาตรฐานมีประโยชน์มากมาย แต่ต้องระวังกรณีพิเศษบางอย่างที่ทำให้เกิดข้อยกเว้น ตัวอย่างเช่นไม่มีคำตอบใดที่ครอบคลุมกรณีที่สตริง C ++ มีอักขระ Unicode บางตัว ในกรณีนี้หากคุณใช้ฟังก์ชันisspaceข้อยกเว้นจะถูกโยนทิ้ง

ฉันใช้รหัสต่อไปนี้เพื่อตัดแต่งสตริงและการดำเนินการอื่น ๆ บางอย่างที่อาจมีประโยชน์ ประโยชน์ที่สำคัญของรหัสนี้คือมันเร็วมาก (เร็วกว่ารหัสใด ๆ ที่ฉันเคยทดสอบ) ใช้เฉพาะไลบรารีมาตรฐานและไม่ทำให้เกิดข้อยกเว้น:

#include <string>
#include <algorithm>
#include <functional>
#include <locale>
#include <iostream>

typedef unsigned char BYTE;

std::string strTrim(std::string s, char option = 0)
{
    // convert all whitespace characters to a standard space
    std::replace_if(s.begin(), s.end(), (std::function<int(BYTE)>)::isspace, ' ');

    // remove leading and trailing spaces
    size_t f = s.find_first_not_of(' ');
    if (f == std::string::npos) return "";
    s = s.substr(f, s.find_last_not_of(' ') - f + 1);

    // remove consecutive spaces
    s = std::string(s.begin(), std::unique(s.begin(), s.end(),
        [](BYTE l, BYTE r){ return l == ' ' && r == ' '; }));

    switch (option)
    {
    case 'l':  // convert to lowercase
        std::transform(s.begin(), s.end(), s.begin(), ::tolower);
        return s;
    case 'U':  // convert to uppercase
        std::transform(s.begin(), s.end(), s.begin(), ::toupper);
        return s;
    case 'n':  // remove all spaces
        s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
        return s;
    default: // just trim
        return s;
    }
}

3

นี่อาจเป็นวิธีที่ง่ายที่สุด

คุณสามารถใช้string::findและstring::rfindเพื่อหาช่องว่างจากทั้งสองด้านและลดสตริง

void TrimWord(std::string& word)
{
    if (word.empty()) return;

    // Trim spaces from left side
    while (word.find(" ") == 0)
    {
        word.erase(0, 1);
    }

    // Trim spaces from right side
    size_t len = word.size();
    while (word.rfind(" ") == --len)
    {
        word.erase(len, len + 1);
    }
}

2

ฉันทดสอบแล้วมันใช้งานได้ทั้งหมด ดังนั้นวิธีการนี้ processInput จะขอให้ผู้ใช้พิมพ์บางสิ่งเข้าไปมันจะส่งคืนสตริงที่ไม่มีช่องว่างภายในหรือช่องว่างเพิ่มเติมเมื่อเริ่มต้นหรือสิ้นสุด หวังว่านี่จะช่วยได้ (ใส่ความคิดเห็นลงไปด้วยเพื่อให้เข้าใจง่าย)

คุณสามารถดูวิธีใช้งานได้ใน main () ที่ด้านล่าง

#include <string>
#include <iostream>

string processInput() {
  char inputChar[256];
  string output = "";
  int outputLength = 0;
  bool space = false;
  // user inputs a string.. well a char array
  cin.getline(inputChar,256);
  output = inputChar;
       string outputToLower = "";
  // put characters to lower and reduce spaces
  for(int i = 0; i < output.length(); i++){
    // if it's caps put it to lowercase
    output[i] = tolower(output[i]);
    // make sure we do not include tabs or line returns or weird symbol for null entry array thingy
    if (output[i] != '\t' && output[i] != '\n' && output[i] != 'Ì') {
      if (space) {
        // if the previous space was a space but this one is not, then space now is false and add char
        if (output[i] != ' ') {
          space = false;
          // add the char
          outputToLower+=output[i];
        }
      } else {
        // if space is false, make it true if the char is a space
        if (output[i] == ' ') {
          space = true;
        }
        // add the char
        outputToLower+=output[i];
      }
    }
  }
  // trim leading and tailing space
  string trimmedOutput = "";
  for(int i = 0; i < outputToLower.length(); i++){
    // if it's the last character and it's not a space, then add it
    // if it's the first character and it's not a space, then add it
    // if it's not the first or the last then add it
    if (i == outputToLower.length() - 1 && outputToLower[i] != ' ' || 
      i == 0 && outputToLower[i] != ' ' || 
      i > 0 && i < outputToLower.length() - 1) {
      trimmedOutput += outputToLower[i];
    } 
  }
  // return
  output = trimmedOutput;
  return output;
}

int main() {
  cout << "Username: ";
  string userName = processInput();
  cout << "\nModified Input = " << userName << endl;
}

2

ทำไมต้องซับซ้อน?

std::string removeSpaces(std::string x){
    if(x[0] == ' ') { x.erase(0, 1); return removeSpaces(x); }
    if(x[x.length() - 1] == ' ') { x.erase(x.length() - 1, x.length()); return removeSpaces(x); }
    else return x;
}

สิ่งนี้ใช้งานได้แม้ว่าการเพิ่มจะล้มเหลวไม่มี regex ไม่มีสิ่งแปลก ๆ หรือไลบรารี

แก้ไข: แก้ไขสำหรับความคิดเห็นของ MM


สิ่งนี้ค่อนข้างไม่มีประสิทธิภาพเมื่อเทียบกับการคำนวณความยาวของช่องว่างและการใช้การเรียกลบเพียงครั้งเดียวสำหรับแต่ละปลาย
MM

1

แนะนำ C ++ 17 std::basic_string_viewซึ่งเป็นเทมเพลตคลาสที่อ้างถึงลำดับที่ต่อเนื่องกันของวัตถุที่มีลักษณะคล้ายถ่านนั่นคือมุมมองของสตริง นอกเหนือจากการมีอินเทอร์เฟซที่คล้ายกันมากstd::basic_stringแล้วยังมีฟังก์ชั่นเพิ่มเติมอีกสองอย่าง: remove_prefix()ซึ่งย่อขนาดมุมมองโดยการเลื่อนเริ่มต้นไปข้างหน้า และ remove_suffix()ซึ่งจะลดขนาดมุมมองโดยการเลื่อนปลายไปด้านหลัง สิ่งเหล่านี้สามารถใช้เพื่อตัดแต่งพื้นที่ส่วนหน้าและส่วนท้าย:

#include <string_view>
#include <string>

std::string_view ltrim(std::string_view str)
{
    const auto pos(str.find_first_not_of(" \t"));
    str.remove_prefix(pos);
    return str;
}

std::string_view rtrim(std::string_view str)
{
    const auto pos(str.find_last_not_of(" \t"));
    str.remove_suffix(str.length() - pos - 1);
    return str;
}

std::string_view trim(std::string_view str)
{
    str = ltrim(str);
    str = rtrim(str);
    return str;
}

int main()
{
    std::string str = "   hello world   ";
    auto sv1{ ltrim(str) };  // "hello world   "
    auto sv2{ rtrim(str) };  // "   hello world"
    auto sv3{ trim(str) };   // "hello world"

    //If you want, you can create std::string objects from std::string_view objects
    auto s1{ sv1 };
    auto s2{ sv2 };
    auto s3{ sv3 };
}

หมายเหตุ: std::string_viewเป็นข้อมูลอ้างอิงที่ไม่ได้เป็นเจ้าของดังนั้นจึงใช้ได้ตราบเท่าที่สตริงเดิมยังคงมีอยู่


0
    char *str = (char*) malloc(50 * sizeof(char));
    strcpy(str, "    some random string (<50 chars)  ");

    while(*str == ' ' || *str == '\t' || *str == '\n')
            str++;

    int len = strlen(str);

    while(len >= 0 && 
            (str[len - 1] == ' ' || str[len - 1] == '\t' || *str == '\n')
    {
            *(str + len - 1) = '\0';
            len--;
    }

    printf(":%s:\n", str);

0
void removeSpaces(string& str)
{
    /* remove multiple spaces */
    int k=0;
    for (int j=0; j<str.size(); ++j)
    {
            if ( (str[j] != ' ') || (str[j] == ' ' && str[j+1] != ' ' ))
            {
                    str [k] = str [j];
                    ++k;
            }

    }
    str.resize(k);

    /* remove space at the end */   
    if (str [k-1] == ' ')
            str.erase(str.end()-1);
    /* remove space at the begin */
    if (str [0] == ' ')
            str.erase(str.begin());
}

0
string trim(const string & sStr)
{
    int nSize = sStr.size();
    int nSPos = 0, nEPos = 1, i;
    for(i = 0; i< nSize; ++i) {
        if( !isspace( sStr[i] ) ) {
            nSPos = i ;
            break;
        }
    }
    for(i = nSize -1 ; i >= 0 ; --i) {
        if( !isspace( sStr[i] ) ) {
            nEPos = i;
            break;
        }
    }
    return string(sStr, nSPos, nEPos - nSPos + 1);
}

0

สำหรับช่องว่างนำหน้าและต่อท้ายวิธีการ:

string string_trim(const string& in) {

    stringstream ss;
    string out;
    ss << in;
    ss >> out;
    return out;

}

หรือสำหรับประโยค:

string trim_words(const string& sentence) {
    stringstream ss;
    ss << sentence;
    string s;
    string out;

    while(ss >> s) {

        out+=(s+' ');
    }
    return out.substr(0, out.length()-1);
}

0

เรียบร้อยและสะอาด

 void trimLeftTrailingSpaces(string &input) {
        input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
            return !isspace(ch);
        }));
    }

    void trimRightTrailingSpaces(string &input) {
        input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
            return !isspace(ch);
        }).base(), input.end());
    }

0

ไม่มีboostไม่regexเพียงstringห้องสมุด มันง่ายมาก

string trim(const string s) { // removes whitespace characters from beginnig and end of string s
    const int l = (int)s.length();
    int a=0, b=l-1;
    char c;
    while(a<l && ((c=s.at(a))==' '||c=='\t'||c=='\n'||c=='\v'||c=='\f'||c=='\r'||c=='\0')) a++;
    while(b>a && ((c=s.at(b))==' '||c=='\t'||c=='\n'||c=='\v'||c=='\f'||c=='\r'||c=='\0')) b--;
    return s.substr(a, 1+b-a);
}

1
... และคุณหลีกเลี่ยงการนำไฟล์ส่วนหัว 2M มาไว้ในบิลด์ของคุณ!
Larry_C

0

หากต้องการเพิ่มปัญหาวิธีขยายการจัดรูปแบบนี้เพื่อประมวลผลช่องว่างเพิ่มเติมระหว่างคำของสตริง

จริงๆแล้วนี่เป็นกรณีที่ง่ายกว่าการคำนวณอักขระช่องว่างนำหน้าและต่อท้ายหลายตัว สิ่งที่คุณต้องทำคือลบอักขระช่องว่างที่ซ้ำกันที่อยู่ติดกันออกจากสตริงทั้งหมด

เพรดิเคตสำหรับพื้นที่สีขาวที่อยู่ติดกันจะเป็น:

auto by_space = [](unsigned char a, unsigned char b) {
    return std::isspace(a) and std::isspace(b);
};

จากนั้นคุณสามารถกำจัดอักขระช่องว่างสีขาวที่อยู่ติดกันที่ซ้ำกันด้วยstd::uniqueและสำนวนลบ - ลบ:

// s = "       This       is       a sample   string     "  
s.erase(std::unique(std::begin(s), std::end(s), by_space), 
        std::end(s));
// s = " This is a sample string "  

สิ่งนี้อาจทำให้อักขระเว้นวรรคเพิ่มเติมที่ด้านหน้าและ / หรือด้านหลัง สิ่งนี้สามารถลบออกได้อย่างง่ายดาย:

if (std::size(s) && std::isspace(s.back()))
    s.pop_back();

if (std::size(s) && std::isspace(s.front()))
    s.erase(0, 1);

นี่คือการสาธิต


-1

ทางออกของฉันสำหรับปัญหานี้ไม่ได้ใช้วิธี STL ใด ๆ แต่มีเพียงวิธีการของสตริง C ++ เท่านั้นดังต่อไปนี้:

void processString(string &s) {
    if ( s.empty() ) return;

    //delete leading and trailing spaces of the input string
    int notSpaceStartPos = 0, notSpaceEndPos = s.length() - 1;
    while ( s[notSpaceStartPos] == ' ' ) ++notSpaceStartPos;
    while ( s[notSpaceEndPos] == ' ' ) --notSpaceEndPos;
    if ( notSpaceStartPos > notSpaceEndPos ) { s = ""; return; }
    s = s.substr(notSpaceStartPos, notSpaceEndPos - notSpaceStartPos + 1);

    //reduce multiple spaces between two words to a single space 
    string temp;
    for ( int i = 0; i < s.length(); i++ ) {
        if ( i > 0 && s[i] == ' ' && s[i-1] == ' ' ) continue;
        temp.push_back(s[i]);
    }
    s = temp;
}

ฉันใช้วิธีนี้เพื่อส่งผ่านปัญหา LeetCode Reverse Words ใน String


-1
void TrimWhitespaces(std::wstring& str)
{
    if (str.empty())
        return;

    const std::wstring& whitespace = L" \t";
    std::wstring::size_type strBegin = str.find_first_not_of(whitespace);
    std::wstring::size_type strEnd = str.find_last_not_of(whitespace);

    if (strBegin != std::wstring::npos || strEnd != std::wstring::npos)
    {
        strBegin == std::wstring::npos ? 0 : strBegin;
        strEnd == std::wstring::npos ? str.size() : 0;

        const auto strRange = strEnd - strBegin + 1;
        str.substr(strBegin, strRange).swap(str);
    }
    else if (str[0] == ' ' || str[0] == '\t')   // handles non-empty spaces-only or tabs-only
    {
        str = L"";
    }
}

void TrimWhitespacesTest()
{
    std::wstring EmptyStr = L"";
    std::wstring SpacesOnlyStr = L"    ";
    std::wstring TabsOnlyStr = L"           ";
    std::wstring RightSpacesStr = L"12345     ";
    std::wstring LeftSpacesStr = L"     12345";
    std::wstring NoSpacesStr = L"12345";

    TrimWhitespaces(EmptyStr);
    TrimWhitespaces(SpacesOnlyStr);
    TrimWhitespaces(TabsOnlyStr);
    TrimWhitespaces(RightSpacesStr);
    TrimWhitespaces(LeftSpacesStr);
    TrimWhitespaces(NoSpacesStr);

    assert(EmptyStr == L"");
    assert(SpacesOnlyStr == L"");
    assert(TabsOnlyStr == L"");
    assert(RightSpacesStr == L"12345");
    assert(LeftSpacesStr == L"12345");
    assert(NoSpacesStr == L"12345");
}

-2

สิ่งที่เกี่ยวกับสำนวนลบลบ ?

std::string s("...");
s.erase( std::remove(s.begin(), s.end(), ' '), s.end() );

ขออภัย. ฉันเห็นว่าสายเกินไปที่คุณไม่ต้องการลบช่องว่างทั้งหมด


สวัสดีตอนนี้คุณทราบแล้วว่าคำตอบนั้นผิดคุณสามารถลบได้หากต้องการ ด้วยวิธีนี้คุณจะได้รับตัวแทนกลับมาที่คุณแพ้จาก DV ในคำตอบนี้ :)
cigien
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.