您的位置:首页 > 健康 > 养生 > 上海新闻最新消息_网站设计报告模板及范文_网站注册账号_武汉网站推广

上海新闻最新消息_网站设计报告模板及范文_网站注册账号_武汉网站推广

2024/10/7 4:22:10 来源:https://blog.csdn.net/hongkid/article/details/142365223  浏览:    关键词:上海新闻最新消息_网站设计报告模板及范文_网站注册账号_武汉网站推广
上海新闻最新消息_网站设计报告模板及范文_网站注册账号_武汉网站推广

在C++中,std::string 是一个非常常用的数据类型,用于处理文本字符串。std::string 提供了丰富的成员函数和操作符,使得字符串处理变得简单而高效。以下是一些常见的 std::string 操作及其示例:

1. 创建字符串

#include <string>
#include <iostream>int main() {std::string s1 = "Hello";       // 直接初始化std::string s2 = s1;            // 复制初始化std::string s3(5, 'a');         // 初始化一个包含5个'a'的字符串std::string s4(s1.begin(), s1.end()); // 从迭代器范围初始化std::cout << s1 << "\n";std::cout << s2 << "\n";std::cout << s3 << "\n";std::cout << s4 << "\n";return 0;
}

2. 获取字符串长度

#include <string>
#include <iostream>int main() {std::string s = "Hello";std::cout << "Length: " << s.length() << "\n";  // 或 s.size()return 0;
}

3. 访问字符串中的字符

#include <string>
#include <iostream>int main() {std::string s = "Hello";std::cout << "First character: " << s[0] << "\n";std::cout << "Last character: " << s[s.length() - 1] << "\n";return 0;
}

4. 连接字符串

#include <string>
#include <iostream>int main() {std::string s1 = "Hello";std::string s2 = "World";std::string s3 = s1 + " " + s2;std::cout << s3 << "\n";return 0;
}

5. 比较字符串

#include <string>
#include <iostream>int main() {std::string s1 = "Hello";std::string s2 = "World";std::string s3 = "Hello";if (s1 == s2) {std::cout << "s1 and s2 are equal\n";} else {std::cout << "s1 and s2 are not equal\n";}if (s1 == s3) {std::cout << "s1 and s3 are equal\n";}if (s1 < s2) {std::cout << "s1 is less than s2\n";}return 0;
}

6. 查找子字符串

#include <string>
#include <iostream>int main() {std::string s = "Hello World";size_t pos = s.find("World");if (pos != std::string::npos) {std::cout << "Found 'World' at position: " << pos << "\n";} else {std::cout << "'World' not found\n";}return 0;
}

7. 替换子字符串

#include <string>
#include <iostream>int main() {std::string s = "Hello World";s.replace(s.find("World"), 5, "C++");std::cout << s << "\n";return 0;
}

8. 插入和删除字符

#include <string>
#include <iostream>int main() {std::string s = "Hello";s.insert(5, " World");  // 在第5个位置插入" World"s.erase(5, 6);          // 从第5个位置开始删除6个字符std::cout << s << "\n";return 0;
}

9. 子字符串

#include <string>
#include <iostream>int main() {std::string s = "Hello World";std::string sub = s.substr(6, 5);  // 从第6个位置开始提取5个字符std::cout << sub << "\n";return 0;
}

10. 字符串流

#include <string>
#include <sstream>
#include <iostream>int main() {std::string s = "123";int num;std::stringstream ss(s);ss >> num;std::cout << "Number: " << num << "\n";return 0;
}

这些是 std::string 中一些最常见的操作。通过这些操作,你可以轻松地进行字符串的创建、访问、连接、比较、查找、替换、插入、删除和提取子字符串等操作。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com