إزالة المسافات البادئة والزائدة من سلسلة في لغة C
غالبًا ما يتضمن معالجة السلسلة في لغة C إزالة المسافات غير الضرورية من السلاسل. يمكن أن يكون هذا مفيدًا بشكل خاص لمهام مثل تنظيف البيانات أو معالجة النصوص.
إزالة المسافات البادئة والزائدة
لإزالة المسافات البادئة والزائدة، يمكن للمرء استخدام find_first_not_of وطرق find_last_not_of. تبحث هذه الوظائف عن الأحرف الأولى والأخيرة التي لا تحتوي على مسافات بيضاء في السلسلة، على التوالي. باستخدام هذه القيم، يمكن للمرء الحصول على السلسلة الفرعية التي تحتوي على أحرف ليست بها مسافات بيضاء:
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); }
إزالة المسافات الزائدة بين الكلمات
لإزالة المسافات الزائدة بين الكلمات، يلزم اتخاذ خطوة إضافية. يمكن تحقيق ذلك باستخدام طرق find_first_of وfind_last_of وfind_first_not_of وfind_last_not_of جنبًا إلى جنب مع substr لاستبدال المسافات الإضافية بمسافة واحدة:
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; }
مثال للاستخدام
يوضح مقتطف الكود التالي استخدام هذه الوظائف:
const std::string foo = " too much\t \tspace\t\t\t "; const std::string bar = "one\ntwo"; std::coutالإخراج:
[too much space] [too much space] [too-much-space] [one two]
تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.
Copyright© 2022 湘ICP备2022001581号-3