21xrx.com
2024-06-03 05:06:15 Monday
登录
文章检索 我的文章 写文章
C++如何去除前导0
2023-07-06 10:57:00 深夜i     --     --
C++ 前导0 字符串处理 字符串转换

在C++中,有时候我们需要从字符串或数字中去除前导0,以便于更好地处理数据或输出结果。下面是一些简单的方法来实现去除前导0的操作。

方法一:使用字符串流

将字符串转换为数字,再将数字转换为字符串,可以实现去除前导0。


#include <sstream>

#include <string>

#include <iostream>

std::string removeLeadingZero(std::string str) {

 int num = atoi(str.c_str());

 std::ostringstream convert;

 convert << num;

 return convert.str();

}

int main() {

 std::string str = "000123";

 std::cout << removeLeadingZero(str) << std::endl;

 return 0;

}

方法二:循环遍历

从字符串的第一个字符开始遍历,直到找到不为0的字符为止。


#include <string>

#include <iostream>

std::string removeLeadingZero(std::string str) {

 int i = 0;

 while (i < str.size() && str[i] == '0') {

  i++;

 }

 return str.substr(i);

}

int main() {

 std::string str = "000123";

 std::cout << removeLeadingZero(str) << std::endl;

 return 0;

}

无论是使用字符串流还是循环遍历,这些方法都可以实现去除前导0的功能。它们也可以适用于其他编程语言。在实际使用中,我们可以根据具体情况选择哪种方法来去除前导0。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复