C++中4种方式把字符串和数字连接起来

以前老用Java里面的String类,用过的人都知道好舒服,连接字符串和数字只需要用一个 + 号就可以了。在这里真的想把C++中string类+号功能加强一下。希望有能力的人可以做一下,不然总是感觉string类缺点啥呢(每次都和java比 O(∩_∩)O哈哈~)
不废话了,如题直接晒代码

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
#include <cstring> 
using namespace std;

//第一种C风格的转化(以前一直喜欢的  sprintf 功能强大)
void test()
{
    char *s = "dong";
    int a = 52;
    float b = .1314;
    char *buf = new char[strlen(s) + sizeof(a) + 1];
    sprintf(buf, "%s%d%.4f", s, a, b);
    printf("%s\n", buf);
}
//半C半C++风格
void test1()
{
    string s = "dong";
    int a = 520;
    char *buf = new char[10];//2147483647 int最大值
    _itoa(a, buf, 10);      //itoa虽然可以转化为各种进制,但是注意不能是float或者double
    cout << s + buf << " | ";
    _itoa(a, buf, 16);
    cout << s + buf << endl;
}
//纯C++风格
void test2()
{
    string s = "陈明东";
    int a = 52;
    double b = .1314;
    ostringstream oss;
    oss << s << a << b;
    cout << oss.str() << endl;
}
//C++11新特性
void test3()
{
    int a = 520;
    float b = 5.20;
    string str = "dong";
    string res = str + to_string(a);
    cout << res << endl;
    res = str + to_string(b);
    res.resize(8);
    cout << res << endl;
}
int main()
{
    test();
    test1();
    test2();
    test3();
    return 0;
}
/*
dong520.1314
dong520 | dong208
陈明东520.1314
dong520
dong5.20
*/
### Java 中实现字符串左补齐的方法 在 Java 中可以通过多种方式来完成字符串的左补齐操作。 一种方法是在 `StringBuilder` 对象中循环添加空格直到达到所需的总长度,之后再追加原始字符串[^1]: ```java String str = "example"; int totalLength = 20; StringBuilder strBuilder = new StringBuilder(); while (strBuilder.length() + str.length() < totalLength) { strBuilder.append(' '); } strBuilder.append(str); System.out.println("'" + strBuilder.toString() + "'"); ``` 另一种更为简洁的方式是利用自定义工具函数来进行左补齐或者右补齐。此函数接收源字符串、目标长度以及用于填充的字符作为参数,并返回处理后的字符串对象[^2]: ```java public static String stringFill(String source, int fillLength, char fillChar, boolean isLeftFill) { if (source == null || source.isEmpty()) { return String.valueOf(fillChar).repeat(Math.max(0, fillLength)); } StringBuilder result = new StringBuilder(source); while(result.length() < fillLength){ if(isLeftFill){ result.insert(0,fillChar); }else{ result.append(fillChar); } } return result.toString(); } // 使用示例 System.out.println(stringFill("hello", 10, '*', true)); // 输出:*****hello ``` 除了上述两种基于 Java 的解决方案外,在某些场景下也可以考虑使用类似于 C 语言中的 `sprintf()` 函数逻辑来构建格式化的字符串。虽然 Java 并不直接提供 `sprintf()` 函数,但是可以借助 `String.format()` 方法模拟其行为[^3]: ```java String formattedStr = String.format("%1$" + totalLength + 's', originalStr).replace(' ', paddingChar); System.out.println(formattedStr); // 假设totalLength=15,paddingChar='-',originalStr="test" // 则输出:-----------test ``` 以上就是在 Java 中几种不同的字符串左补齐方案。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值