字符串、字符数组、字符、整型 等 一些操作

C++中字符数组与string的相互转换

字符数组转化成string类型

char ch [] = "ABCDEFG";
string str(ch);//也可string str = ch;
或者
char ch [] = "ABCDEFG";
string str;
str = ch;//在原有基础上添加可以用str += ch;

将string类型转换为字符数组

char buf[10];
string str("ABCDEFG");
length = str.copy(buf, 9);
buf[length] = '\0';
或者
char buf[10];
string str("ABCDEFG");
strcpy(buf, str.c_str());//strncpy(buf, str.c_str(), 10);

还可以使用stringstream来转换


c++字符串长度求法(string,char*)


/*
(1)length():最直接字符串长度
(2)size():字符串长度(类似string内char元素个数)
(3)strlen(char*):函数求的是字符串的实际长度,它求得方法是从开始到遇到第一个’\0’,
如果你只定义没有给它赋初值,这个结果是不定的,它会从aa首地址一直找下去,直到遇到’\0’停止。
*/
//(1)length()
#include <string>
string user;
int len = user.length();

//(2)size()
#include <string>
string user;
int len = user.size();
//strlen同样也可以用于C++的string。但是需要用c_str()将C++ string转换为char*类型

//(3)strlen()
#include <string>
 string str = "abc"; char cstr[20]; 
 strcpy(cstr,str.c_str()); 
 cout << strlen(cstr) << endl; return 0;

substr()

string sub1 = s.substr(pos); //从pos至结尾;

string sub2 = s.substr(pos, len); //从下标为pos开始截取长度为len的子字符串;

atoi()函数

int atoi(const char *str );

函数功能:把字符串转换成整型数。
参数str:要进行转换的字符串
返回值:每个函数返回 int 值,此值由将输入字符作为数字解析而生成。 如果该输入无法转换为该类型的值,则atoi的返回值为 0。
注意:使用该函数时要注意atoi返回的是int类型,注意输入str的范围不要超出int类型的范围。

itoa()

 char *itoa( int value, char *string,int radix);

功能:将整数value 转换成字符串存入string 指向的内存空间 ,radix 为转换时所用基数(保存到字符串中的数据的进制基数)。
原型说明:
输入参数:
value:要转换的数据。
string:目标字符串的地址。
radix:转换后的进制数,可以是10进制、16进制等,范围必须在 2-36。
返回值:函数返回一个指向 str,无错误返回。

atoi stoi
注意:itoa不是一个标准的c函数,他是windows特有的,跨平台写程序,要用sprintf。
①atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char类型的,而stoi()的参数是const string,不需要转化为 const char*;

#include <iostream>
#include <string>
 
using namespace std;
 
int main()
 
{
 
    string s1 = "2147482", s2 = "-214748";
 
    string s3 = "214748666666663", s4 = "-21474836488";
 
    cout << stoi(s1) << endl;
 
    cout << stoi(s2) << endl;
 
    cout << atoi(s3.c_str()) << endl;
 
    cout << atoi(s4.c_str()) << endl;
 
    system("pause");
 
    return 0;
 
}

c++中**c_str()**的用法详解

标准库的string类提供了三个成员函数来从一个string得到c类型的字符数组
主要介绍c_str
c_str():生成一个const char*指针,指向以空字符终止的数组。
这个数组应该是string类内部的数组

#include <iostream>
//需要包含cstring的字符串
#include <cstring>
using namespace std;
 
int main()
{
    //string-->char*
    //c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同
 
    //这个数组的数据是临时的,当有一个改变这些数据的成员函数被调用后,其中的数据就会失效。
    //因此要么现用先转换,要么把它的数据复制到用户自己可以管理的内存中
    const char *c;
    string s = "1234";
    c = s.c_str();
    cout<<c<<endl;
    s = "abcde";
    cout<<c<<endl;
}

to_string()
c++ 11起支持

std::string to_string(int value); (1) (C++11)
std::string to_string(long value); (2) (C++11)
std::string to_string(long long value); (3) (C++11)
std::string to_string(unsigned value); (4) (C++11)
std::string to_string(unsigned long value); (5) (C++11)
std::string to_string(unsigned long long value); (6) (C++11)
std::string to_string(float value); (7) (C++11)
std::string to_string(double value); (8) (C++11)
std::string to_string(long double value); (9) (C++11)

sprintf
功 能: 送格式化输出到字符串中
用 法: sprintf(char *string, char *farmat [,argument,…]);
程序例:

#include
#include
int main(void)
{
   char buffer[80];
   sprintf(buffer, "An approximation ofPi is %f\n", M_PI);
   puts(buffer);
   return 0;
}

strcat()
功能:将两个字符串连接(拼接)起来。

char*strcat(char* strDestination, const char* strSource);

头文件:string.h
语法/原型:
参数说明:
strDestination:目的字符串;
strSource:源字符串。
strcat() 函数把 strSource 所指向的字符串追加到 strDestination 所指向的字符串的结尾,所以必须要保证 strDestination 有足够的内存空间来容纳两个字符串,否则会导致溢出错误。
注意:strDestination 末尾的\0会被覆盖,strSource 末尾的\0会一起被复制过去,最终的字符串只有一个\0。
返回值:指向 strDestination 的指针。

isdigit()

功能:检查c是否为十进制数字字符。

int isdigit ( int c );
Checks whether c is a decimal digit character.

/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
  char str[]="1776ad";
  int year;
  if (isdigit(str[0]))
  {
    year = atoi (str);
    printf ("The year that followed %d was %d.\n",year,year+1);
  }
  return 0;}

sscanf()

C 库函数sscanf从字符串读取格式化输入。

 int sscanf(const char *str, const char *format, ...) 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int day, year;
   char weekday[20], month[20], dtm[100];

   strcpy( dtm, "Saturday March 25 1989" );
   sscanf( dtm, "%s %s %d  %d", weekday, month, &day, &year );

   printf("%s %d, %d = %s\n", month, day, year, weekday );
    
   return(0);
}

让我们编译并运行上面的程序,这将产生以下结果:

March 25, 1989 = Saturday

ostringstream 和 istringstream

剑指 Offer 37. 序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树。

 // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            TreeNode* tmp =q.front();
            q.pop();
            if(tmp==NULL)
                out<<"null ";
            else{
                out<<tmp->val<<" ";
                q.push(tmp->left);
                q.push(tmp->right);
            }
                
        }
        return out.str();
    }
 // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream input(data);
        string val;
        vector<TreeNode*> vec;
        while(input>>val){
            if(val=="null")
                vec.push_back(NULL);
            else
                vec.push_back(new TreeNode(stoi(val)));
        }
        int j=1;
        for(int i=0;i<vec.size();++i){
            if(vec[i]==NULL) 
                continue;
            if(j<vec.size())
                vec[i]->left = vec[j++];
            if(j<vec.size())
                vec[i]->right = vec[j++];
        }
        return vec[0];
    }

getline()函数
原型:

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

也可以从流中读取
**

assign()

**
C++ string assign()赋值常用方法
函数assign()常用在给string类变量赋值.
常用方法有:
1,直接用另一个字符串赋值.
如str2.assign(str1);即用str1给str2赋值.
2,用另一个字符串的一个子串赋值
如str3.assign(str1, 2, 3);
3,用一个字符串的前一段子串赋值;
如str4.assign(“World”, 5);
4,用几个相同的字符,赋值.
如str5.assign(10, ‘c’);
容器迭代器

lower_bound
upper_bound

class Solution {
public:
    int findSpecialInteger(vector<int>& arr) {
        int n = arr.size();
        int span = n / 4 + 1;
        for (int i = 0; i < n; i += span) {
            auto iter_l = lower_bound(arr.begin(), arr.end(), arr[i]);
            auto iter_r = upper_bound(arr.begin(), arr.end(), arr[i]);
            if (iter_r - iter_l >= span) {
                return arr[i];
            }
        }
        return -1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值