javaer学c++: c++中的字符串

[size=medium]
c++中的字符串也是一个比较坑爹的地方, 不像java中的字符串使用起来非常的方便, 可以用难用和容易出错来形容. 难用也没办法, 字符串是编程时必须要用到的一个东西, 是不可避免的.

c++中的字符串的坑爹的地方:
(1)不是基础数据类型, 不像java那样有一个很好用的String类. (有人要说了, c++中不是有string类么, 不过那个string类并不是和java中的String类对等的, 他可以看作是一个动态的char数组而已).
(2)字符串是用数组来表示的, 且默认字符串上不带字符串长度的属性. (java中有length()这个方法来很方便的获取字符串的长度)
(3)字符串的拼接不能简单的使用+来进行.


(1)c++中的字符串:
[/size]
Main.cpp

int main(void)
{
char str[] = "this is a str";
int length = sizeof(str) / sizeof(char); // 求出字符串长度
return 0;
}


[size=medium]
(2)字符串的打印, 这个还算方便, c++中的cout重载了大部分的操作符来输出各种数据类型.
[/size]
Main.cpp

#include <iostram>
#include <stdio.h>

using namespace std;

int main(void)
{
float f = 1.0f;
int i = 0;
bool b = false;
char c = 'a';
char str[] = "hello";

cout << "float:" << f << ",int:" << i << ",bool:" << b << ",char:" << c << ",str:" << str << '\n';

printf("float:%f,int:%d,bool:%d,char:%c,str:%s", f, i, b, c, str);
return 0;
}



[size=medium]
(3)字符串的拼接, java中可以简单的使用+来完成字符串的拼接, c++中不行, 必须使用sprintf函数

java中这样拼接字符串:
[/size]
Main.java

public class Main {
public static void main(String[] args) {
int i = 0;
float f = 1.0;
boolean b = false;
char c = 'a';
String str = "int:" + i + ",float:" + f + ",boolean:" + b + ",char:" + c;
System.out.println(str);
}
}


Main.cpp

#include <iostream>
using namespace std;

int main(void)
{
int i = 0;
float f = 1.0f;
bool b = false;
char c = 'a';

char str[100];
sprintf(str, "int:%d,float:%f,bool:%s,char:%c", i, f, (b ? "true" : "false"), c);
cout << str << '\n';
return 0;
}



[size=medium]
c++中的string类的使用(就是一个动态的char数组)
[/size]
Main.cpp

#include <string>
#include <iostream>

using namespace std;

int main(void)
{
// 未完, 待续
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值