string与字符串的转换

本文详细介绍了在C++中如何从文件读取字符串,使用getline()函数的不同形式,以及如何将string转换为字符串类型。同时,讨论了strtok()函数在分割字符串中的应用,提供了一系列实例来辅助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、从文件中读取字符串

即是getline的用法。

1、在中的getline()函数有两种重载形式

stream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

2、 在中的getline函数有四种重载形式

用法和上第一种类似,但是读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。

istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);

3、从文件中读取序列

打开文件,将序列写入到string中

ifstream inflie;
string s1;
inflie.open("file.txt", ios::in);
//先存到string中
getline(inflie,s1);

四、将string转为字符串类型。

头文件:#include <string.h> 和 #include <stdio.h>
功能:把从src地址开始且含有NULL结束符的字符串复制到以dest开始的地址空间
说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
返回指向dest的指针。

char *strcpy(char* dest, const char *src);

将string转为字符串

//string 转字符串
const int len = s1.length();
s = new char[len + 1];
strcpy(s, s1.c_str());

五、使用strtok()分割字符串

char *strtok(char s[], const char *delim);

功能:分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。
注意:如果传入字符串,则传入的字符串中每个字符均为分割符。首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL。

示例

include<iostream>
#include<cstring>
using namespace std;
int main()
{
    char sentence[]="This is a sentence with 7 tokens";
    cout << "The string to be tokenized is:\n" << sentence << "\n\nThe tokens are:\n\n";
    char *tokenPtr=strtok(sentence," ");
    while(tokenPtr!=NULL) {
        cout<<tokenPtr<<endl;
        tokenPtr=strtok(NULL," ");//第二次调用需要将s设置为NULL
    }
    //cout << "After strtok,sentence=" << tokenPtr<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值