字符串处理大数据小结

这篇博客是一位软件工程专业的学生对字符串处理大数据的总结,包括用C++在Windows环境下使用vs2008进行编程。内容涵盖大数相加、相乘、相除、指数运算以及转换等操作,通过实例展示了算法的实现和结果。

字符串处理大数据小结

 

个人信息:就读于燕大本科软件工程专业 目前大三;

本人博客:google搜索“cqs_2012”即可;

个人爱好:酷爱数据结构和算法,希望将来搞科研为人民作出自己的贡献;

博客内容:字符串处理大数据小结;

博客时间:2014-3-27

编程语言:C++

编程坏境:Windows

编程工具:vs2008

 

  • 引言

今天本想做题的,把英雄会上一个题目做出来,后来发现要用到自己以前写过的字符串处理函数,故就把以前的字符串函数总结一下,写了一些简明的注释,方便自己和大家用,特分享于此。

  • 知识总结

1.我们都知道整形数据是有范围限制的,当超过整形表示范围后,可能溢出,所以用强大的字符串来处理大型数据是非常有用的,我们不着急于我们怎么去处理大数据,从小的做起,用字符串的形式模拟两个整数相加

程序结果演示如下

看完结果感觉还行吧,说明如下

	// function 1: mode the add of int( (-3) + (-3) ) = - 6
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相加操作,结果存在返回的字符串里


代码如下

// mode the add of int
string String::ADD_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input ADD_Int";
	}
	Standardization(a);
	Standardization(b);	

	if(a[0] != '-' && b[0] != '-')
		return AddInt(a,b);
	else if(a[0] != '-'&& b[0] == '-')		
		return MinusInt( a,b.substr( 1,b.size() ) );
	else if(a[0] == '-'&& b[0] != '-')
		return MinusInt(b,a.substr(1,a.size()));
	else return '-'+AddInt(a.substr(1,a.size()),b.substr( 1,b.size() ));
};


2.整形大数

程序结果截图如下

代码说明如下

	// function 2: make a-b mode int a - b; 7 - (-3) = 10
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相减操作,结果存在返回的字符串里


算法代码如下

// make a-b mode int a - b;
string String::MINUS_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input Multiplies_Int";
	}
	Standardization(a);
	Standardization(b);	
	if(a[0] != '-' && b[0] != '-')
		return MinusInt(a,b);
	else if(a[0] != '-' && b[0] == '-')
		return AddInt(a,b.substr(1,b.size()));
	else if(a[0] == '-' && b[0] != '-')
		return "-"+AddInt(a.substr(1,a.size()),b);
	else return MinusInt( b.substr(1,b.size()) , a.substr(1,a.size()) );
};


3.整形大数相乘

程序运行结果如下

函数说明如下

	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相乘操作,结果存在返回的字符串里


算法代码如下;

// make a*b mode int a * b;
string String::MULT_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input Multiplies_Int";
	}
	Standardization(a);
	Standardization(b);	
	string::size_type i = a.size(),j = b.size();
	string c = "0",d = "";
	bool fushu = (a[0] == '-' && b[0] != '-')||(a[0] != '-' && b[0] == '-');
	if(a[0] == '-')	
		a = a.substr(1,a.size());		
	if(b[0] == '-')	
		b = b.substr(1,b.size());

	int jinwei = 0;
	for( j = b.size()-1 ; j < b.size() ;j--)
	{
		// each number of b to * a 
		jinwei = 0;
		for( i = a.size()-1 ; i < a.size() ;i-- )
		{
			d = IntToChar(   ( CharToNumber(a[i]) * CharToNumber(b[j]) + jinwei ) % 10 )+ d ;
			jinwei = ( CharToNumber(a[i]) * CharToNumber(b[j]) + jinwei ) / 10 ;
		}
		if(jinwei)
			d = IntToChar(jinwei) +d;
		// add all number result
		c = ADD_Int(c,d);
		d = "";
		unsigned int zero = 0 ;
		while( zero < b.size() - j )
		{
			d = d + '0';
			zero ++;
		}

	}

	Standardization(c);
	if( fushu && c != "0" )
		return '-'+c;
	else return c;
};

4.整形大数做除法

程序运行如下

函数说明性文档如下

	// function 4: mode the division a/b
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相除操作,结果存在返回的字符串里


算法代码实现如下

// mode the division a/b
string String::DIV_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return "0";
	else if( b.empty() )
		return "e";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input DIV_Int";
	}
	Standardization(a);
	Standardization(b);	
	if(b == "0")
		return "e";
	bool fushu =  (a[0] == '-' && b[0] != '-')||(a[0] != '-' && b[0] == '-');
	if( a[0] == '-' )	
		a = a.substr(1,a.size());		
	if( b[0] == '-' )	
		b = b.substr(1,b.size());
	if( Compare(a,b) == '<' )
		return "0";


	string yushu = "";

	string beichushu = a.substr(0,b.size());	
	string shang = Division( beichushu , b);
	yushu =  MinusInt( beichushu ,MULT_Int( shang, b) );
	string c = shang;

	for(string::size_type i = b.size(); i<a.size(); i++)
	{	
		// beichushu = (yushu * 10 + a.substr(i,b.size())) 
		// shang = beichushu/ b;
		// c = c + shang;
		// yushu = beichushu  - b* shang;
		beichushu =   yushu+ a[i]     ;
		shang = Division( beichushu , b);
		c = c + shang;			
		yushu =  MinusInt( beichushu ,MULT_Int( shang, b) );
	}
	Standardization(c);
	return fushu?('-'+c):c;
};


5.指数运算

程序运行结果如下

哥们,看到这你有什么感想?别喷我是疯子,我也不怕喷,我就是疯子,是疯子推动了IT行业的发展。

哈哈,函数说明如下

	// function 5: pow number a^b
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的a^b操作,结果存在返回的字符串里


算法代码演示如下

// function: pow number x,y
string String::Pow_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return "0";
	else if( b.empty() )
		return "e";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input DIV_Int";
	}
	Standardization(a);
	Standardization(b);	
	string result = "1" ;
	if(Compare(b,"0") != '<')
		for(string i ="0" ;Compare(i,b) == '<' ;i = AddInt(i,"1"))
		{
			result = MULT_Int(result,a);
		}
	else 
		for(string i ="0" ;Compare(i,b) == '>' ;i = MINUS_Int(i,"1"))
		{
			result = DIV_Int(result,a);
		}
		return result ;
};


6.整形数转换成字符串格式

程序运行结果如下

 

如果输入小数会如下

显然很不理想哈

函数文档说明如下

	// function 6: int To string :"123" = 123
	// input: 一个int数 a;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 将整数a转换成对应的字符串格式


算法代码实现如下

// function : int To string 
string String::Int_To_String(int x)
{
	bool fushu = false;
	string result="";
	if(x < 0 )
	{
		fushu = true ;
		x = -x;
	}
	else if( x == 0 )
		return "0";
	while(x)
	{
		result = IntToChar(x % 10) + result;
		x = x/10;
	}
	if(fushu)
		result = "-"+result;
	return result;
};


7.实现比较操作

程序运行结果如下

函数说明性文档如下

	// function 13: compare string a and b
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符,字符里是a和b的大小关系;
	// 功能: 实现参数两个整数的a和b比较操作,结果< or = or >存在返回的字符里


算法代码实现如下

// compare string a and b
char String::Compare(string a,string b)
{
	if(a.empty() || b.empty())
	{
		cout<<"error of input compare";
		return 'e';
	}
	else
	{

		if(!check_all_number(a) || !check_all_number(b))
		{
			return 'e';
		}
		Standardization(a);
		Standardization(b);
		if(a[0] == '-' && b[0] != '-')
			return '<';
		else if( a[0] != '-' && b[0] == '-')
			return '>';
		bool fushu = (a[0] == '-');

		if(a.size() > b.size() )
			return fushu?'<':'>';
		else if(a.size() == b.size())
		{
			for(string::size_type i = 0;i < a.size(); i++)
			{
				if(a[i] > b[i])
					return fushu?'<':'>';
				if(a[i] < b[i])
					return fushu?'>':'<';
			}
			return '=';
		}			
		return fushu?'>':'<';
	}
};


8.实现标准string的数据转换成int 型对应的数据

程序运行结果截图如下

函数文档说明如下

	// function 15: make string(>0) into standard int number
	// input: 一个字符串 a,里面放的是一个整数;
	// output: 返回一个字符串,字符串里是a对应的整形数据;
	// 功能: 将存在字符串里的整数取出来,放在整形容器里,然后返回,根据返回的结果可以判定是否转换成功


算法思路代码实现如下

// make string(>0) into standard int number
std::pair<bool,int> String::String_into_intNumber(string &a)
{
	if(Standardization(a))
	{
		string max = Int_To_String(numeric_limits<int>::max()-1);
		bool fushu = false;
		if(a[0] == '-')
		{
			fushu = true ;
			a = a.substr(1,a.length());
		}
		if(Compare(a,max) != '<')
		{
			cout<<"溢出 exception"<<endl;
			return std::make_pair(false,0);
		}
		int result = 0 ;
		for(size_t i =0;i<a.length();i++)
		{
			result = result * 10 + CharToNumber(a[i]);
		}
		if(fushu)
			result = - result;
		return std::make_pair(true,result);
	}
	else
	{
		cout<<"exception of function String_into_intNumber input"<<endl;
		return std::make_pair(false,0);
	}
};

over 

  • 总的代码

有的函数过于简单,故没有一一列出,小的函数在下面我派生的类里,代码如下

#include <iostream>
#include <string>
#include <limits>
using namespace std;

// extra the class of string
class String:public string
{
public:

	// function 1: mode the add of int( (-3) + (-3) ) = - 6
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相加操作,结果存在返回的字符串里
	static string ADD_Int(string a,string b);



	// function 2: make a-b mode int a - b; 7 - (-3) = 10
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相减操作,结果存在返回的字符串里
	static string MINUS_Int(string a,string b);

	// function 3: make a*b mode int a * b;
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相乘操作,结果存在返回的字符串里
	static string MULT_Int(string a,string b);

	// function 4: mode the division a/b
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的相除操作,结果存在返回的字符串里
	static string DIV_Int(string a,string b);

	// function 5: pow number a^b
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 实现参数两个整数的a^b操作,结果存在返回的字符串里
	static string Pow_Int(string a,string b);

	// function 6: int To string :"123" = 123
	// input: 一个int数 a;
	// output: 返回一个字符串,字符串里面是整数;
	// 功能: 将整数a转换成对应的字符串格式
	static string Int_To_String(int x);

	// function 7: static char division a/b : 4 / 3
	static string Division(string a,string b);

	// function 8: make a-b mode int a - b; 4 - 3
	static string MinusInt(string a,string b);

	// function 9: mode the add of int :3 + 4
	static string AddInt(string a,string b);

	// function 10: make char to the int number :'9' = 9
	static int CharToNumber(char c);

	// function 11: make int to the model char : 7 = '7'
	static string IntToChar(int i);

	// function 12: check whether the string is legal 
	static bool check_all_number(string a);

	// function 13: compare string a and b
	// input: 两个字符串 a 和 b,里面放的都是整数;
	// output: 返回一个字符,字符里是a和b的大小关系;
	// 功能: 实现参数两个整数的a和b比较操作,结果< or = or >存在返回的字符里
	static char Compare(string a,string b);

	// function 14: make string into standard string number
	static bool Standardization(string &a);

	// function 15: make string(>0) into standard int number
	// input: 一个字符串 a,里面放的是一个整数;
	// output: 返回一个字符串,字符串里是a对应的整形数据;
	// 功能: 将存在字符串里的整数取出来,放在整形容器里,然后返回,根据返回的结果可以判定是否转换成功
	static std::pair<bool,int> String_into_intNumber(string &a);
};



// mode the add of int
string String::ADD_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input ADD_Int";
	}
	Standardization(a);
	Standardization(b);	

	if(a[0] != '-' && b[0] != '-')
		return AddInt(a,b);
	else if(a[0] != '-'&& b[0] == '-')		
		return MinusInt( a,b.substr( 1,b.size() ) );
	else if(a[0] == '-'&& b[0] != '-')
		return MinusInt(b,a.substr(1,a.size()));
	else return '-'+AddInt(a.substr(1,a.size()),b.substr( 1,b.size() ));
};







// make a-b mode int a - b;
string String::MINUS_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input Multiplies_Int";
	}
	Standardization(a);
	Standardization(b);	
	if(a[0] != '-' && b[0] != '-')
		return MinusInt(a,b);
	else if(a[0] != '-' && b[0] == '-')
		return AddInt(a,b.substr(1,b.size()));
	else if(a[0] == '-' && b[0] != '-')
		return "-"+AddInt(a.substr(1,a.size()),b);
	else return MinusInt( b.substr(1,b.size()) , a.substr(1,a.size()) );
};






// make a*b mode int a * b;
string String::MULT_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input Multiplies_Int";
	}
	Standardization(a);
	Standardization(b);	
	string::size_type i = a.size(),j = b.size();
	string c = "0",d = "";
	bool fushu = (a[0] == '-' && b[0] != '-')||(a[0] != '-' && b[0] == '-');
	if(a[0] == '-')	
		a = a.substr(1,a.size());		
	if(b[0] == '-')	
		b = b.substr(1,b.size());

	int jinwei = 0;
	for( j = b.size()-1 ; j < b.size() ;j--)
	{
		// each number of b to * a 
		jinwei = 0;
		for( i = a.size()-1 ; i < a.size() ;i-- )
		{
			d = IntToChar(   ( CharToNumber(a[i]) * CharToNumber(b[j]) + jinwei ) % 10 )+ d ;
			jinwei = ( CharToNumber(a[i]) * CharToNumber(b[j]) + jinwei ) / 10 ;
		}
		if(jinwei)
			d = IntToChar(jinwei) +d;
		// add all number result
		c = ADD_Int(c,d);
		d = "";
		unsigned int zero = 0 ;
		while( zero < b.size() - j )
		{
			d = d + '0';
			zero ++;
		}

	}

	Standardization(c);
	if( fushu && c != "0" )
		return '-'+c;
	else return c;
};




// mode the division a/b
string String::DIV_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return "0";
	else if( b.empty() )
		return "e";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input DIV_Int";
	}
	Standardization(a);
	Standardization(b);	
	if(b == "0")
		return "e";
	bool fushu =  (a[0] == '-' && b[0] != '-')||(a[0] != '-' && b[0] == '-');
	if( a[0] == '-' )	
		a = a.substr(1,a.size());		
	if( b[0] == '-' )	
		b = b.substr(1,b.size());
	if( Compare(a,b) == '<' )
		return "0";


	string yushu = "";

	string beichushu = a.substr(0,b.size());	
	string shang = Division( beichushu , b);
	yushu =  MinusInt( beichushu ,MULT_Int( shang, b) );
	string c = shang;

	for(string::size_type i = b.size(); i<a.size(); i++)
	{	
		beichushu =   yushu+ a[i]     ;
		shang = Division( beichushu , b);
		c = c + shang;			
		yushu =  MinusInt( beichushu ,MULT_Int( shang, b) );
	}
	Standardization(c);
	return fushu?('-'+c):c;
};





// function: pow number x,y
string String::Pow_Int(string a,string b)
{
	// exception of input
	if( a.empty() )
		return "0";
	else if( b.empty() )
		return "e";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input DIV_Int";
	}
	Standardization(a);
	Standardization(b);	
	string result = "1" ;
	if(Compare(b,"0") != '<')
		for(string i ="0" ;Compare(i,b) == '<' ;i = AddInt(i,"1"))
		{
			result = MULT_Int(result,a);
		}
	else 
		for(string i ="0" ;Compare(i,b) == '>' ;i = MINUS_Int(i,"1"))
		{
			result = DIV_Int(result,a);
		}
		return result ;
};






// function : int To string 
string String::Int_To_String(int x)
{
	bool fushu = false;
	string result="";
	if(x < 0 )
	{
		fushu = true ;
		x = -x;
	}
	else if( x == 0 )
		return "0";
	while(x)
	{
		result = IntToChar(x % 10) + result;
		x = x/10;
	}
	if(fushu)
		result = "-"+result;
	return result;
};





// static char division a/b
string String::Division(string a,string b)
{
	// exception of input
	if( a.empty() )
		return "0";
	else if( b.empty() )
		return "e";
	if(!check_all_number(a) || !check_all_number(b))
	{
		cout<<"exception of input Division"<<endl;
		return "e";
	}
	Standardization(a);
	Standardization(b);	
	int i = 0;
	while( i<=9 )
	{
		// if a - b*i < b
		if(  Compare(   MINUS_Int(   a  ,   MULT_Int(IntToChar(i),b)    ) , b ) == '<'    )
			break;
		i++;
	}
	if( i>9 )
		return "e";
	return ""+IntToChar(i);
};






// make a-b mode int a - b;
string String::MinusInt(string a,string b)
{
	// exception of input
	if(!check_all_number(a) || !check_all_number(b))
		return "exception of input MinusInt";
	Standardization(a);
	Standardization(b);
	// particular string of input
	if(a.empty())
	{
		if(b.empty())
			return "0";
		else
			return "-"+b;
	}
	else if(b.empty())
	{
		return a;
	}

	// normal number a < b
	string c = "";
	bool check = true ;
	if(Compare(a,b) == '=')
		return "0";
	else if(Compare(a,b) == '<')
	{
		c = a ;
		a = b ;
		b = c ;
		c = "";
		check = false ;
	}
	// normal number a >= b
	string::size_type i = a.size()-1, j = b.size()-1;
	int jiewei = 0,now;

	while(i < a.size() && j < b.size())
	{
		now = CharToNumber(a[i]) - CharToNumber(b[j]) - jiewei ;

		if( now < 0 )
		{
			jiewei = 1;
			now = 10 + now ;
		}
		else jiewei = 0;
		c = IntToChar(now)  + c ;
		i--;j--;
	}
	while(i < a.size())
	{
		now = CharToNumber(a[i]) - jiewei ;
		if( now < 0 )
		{
			jiewei = 1;
			now = 10 + now ;
		}
		else jiewei = 0;
		c = IntToChar( now )  + c ;
		i--;
	}
	Standardization(c);
	if(!check)
		c = '-' + c;		
	return c; 
};







// mode the add of int
string String::AddInt(string a,string b)
{
	// exception of input
	if( a.empty() )
		return b;
	else if( b.empty() )
		return "0";
	if(!check_all_number(a) || !check_all_number(b))
	{
		return "exception of input AddInt";
	}
	Standardization(a);
	Standardization(b);
	string::size_type i = a.size()-1 ,j = b.size()-1 , k = 0 ;
	string c = "";
	int jinwei = 0;
	while( i < a.size() && j < b.size() )
	{
		c = IntToChar( ( CharToNumber(a[i]) + CharToNumber(b[j]) + jinwei ) % 10 ) + c;
		jinwei = ( CharToNumber(a[i]) + CharToNumber(b[j]) + jinwei ) / 10;
		j--;i--;
	}
	while( j < b.size()  )
	{
		c =  IntToChar( ( CharToNumber(b[j]) + jinwei ) % 10 ) + c;
		jinwei = ( jinwei + CharToNumber(b[j]) ) / 10;	
		j--;
	}
	while( i < a.size() )
	{
		c =  IntToChar( ( CharToNumber(a[i]) + jinwei ) % 10 ) + c;
		jinwei = ( jinwei + CharToNumber(a[i]) ) / 10;	
		i--;
	}
	if( jinwei )
		c = IntToChar(  jinwei  ) + c;
	Standardization(c);
	return c;
};







// make char to the int number
int String::CharToNumber(char c)
{
	if( c >= '0' && c <= '9' )
		return int(c - '0');
	else 
	{
		cout<<c<<" exception of input CharToNumber "<<endl;
		system("pause");
		return 0;
	}
};







// make int to the model char
string String::IntToChar(int i)
{
	if( i >= 0 && i <= 9 )
	{
		string c = "";
		return c+char(i+48);
	}
	else
	{
		cout<<i<<" exception of input IntToChar"<<endl;
		system("pause");
		return "e";
	}
};






// check whether the string is legal 
bool String::check_all_number(string a)
{
	if(a.empty())
		return true ;
	string::size_type L = a.size(),i = 0;
	if(a[0] == '-')
		i++;
	while( i < L )
	{
		if( a[i] < '0' || a[i] > '9')
			return false;
		i++; 
	}
	return true ;
};







// compare string a and b
char String::Compare(string a,string b)
{
	if(a.empty() || b.empty())
	{
		cout<<"error of input compare";
		return 'e';
	}
	else
	{

		if(!check_all_number(a) || !check_all_number(b))
		{
			return 'e';
		}
		Standardization(a);
		Standardization(b);
		if(a[0] == '-' && b[0] != '-')
			return '<';
		else if( a[0] != '-' && b[0] == '-')
			return '>';
		bool fushu = (a[0] == '-');

		if(a.size() > b.size() )
			return fushu?'<':'>';
		else if(a.size() == b.size())
		{
			for(string::size_type i = 0;i < a.size(); i++)
			{
				if(a[i] > b[i])
					return fushu?'<':'>';
				if(a[i] < b[i])
					return fushu?'>':'<';
			}
			return '=';
		}			
		return fushu?'>':'<';
	}
};







// make string into standard string number
bool String::Standardization(string &a)
{
	if(!check_all_number(a))
	{
		cout<<a<<" exception of input Standardization"<<endl;
		return false;
	}
	string::size_type i = 0;
	bool fushu = false ;
	if( a[0] == '-' )
	{
		fushu = true;
		i = 1;
	}
	while(i < a.size())
	{
		if(a[i] != '0')
			break;
		i++;
	}
	if(i == a.size())
		i--;
	a = a.substr(i,a.size());
	if( fushu && a != "0")
		a = '-' + a;
	return true ;
};







// make string(>0) into standard int number
std::pair<bool,int> String::String_into_intNumber(string &a)
{
	if(Standardization(a))
	{
		string max = Int_To_String(numeric_limits<int>::max()-1);
		bool fushu = false;
		if(a[0] == '-')
		{
			fushu = true ;
			a = a.substr(1,a.length());
		}
		if(Compare(a,max) != '<')
		{
			cout<<"溢出 exception"<<endl;
			return std::make_pair(false,0);
		}
		int result = 0 ;
		for(size_t i =0;i<a.length();i++)
		{
			result = result * 10 + CharToNumber(a[i]);
		}
		if(fushu)
			result = - result;
		return std::make_pair(true,result);
	}
	else
	{
		cout<<"exception of function String_into_intNumber input"<<endl;
		return std::make_pair(false,0);
	}
};


 

 

<think>首先,用户的问题是:“我想查找在pandas中进行字符串拼接的方法 请问pandas中字符串拼接的方法”。这是一个直接的查询关于pandas库中进行字符串拼接的方法。 回顾系统指令: - 所有行内数学表达式使用 `$...$` 格式。 - 独立公式使用 `$$...$$` 格式。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如 `[^1]`。 - 回答结构清晰,帮助用户逐步解决问题。 - 参考站内引用:用户提供了三个引用:[^1], [^2], [^3]。 用户提供的引用: - [^1]: 讨论使用 `cat()` 函数以拼接字符串方式合并列。 - [^2]: 关于Pandas处理字符串的一般方法,包括清洗、转换、提取、拼接等。 - [^3]: 具体示例使用 `.str.cat()` 方法将两列字符串拼接到一起。 用户的问题是关于pandas中字符串拼接的方法,所以我需要基于这些引用构建回答。 关键点: - 引用[^1]和[^3]都提到了`.str.cat()`方法。 - 引用[^2]提到字符串拼接和连接。 - 引用[^1]强调了使用`cat()`函数(可能指的是`.str.cat()`)。 - 引用[^3]提供了一个具体示例:`df['date'].str.cat(df['hour'])`。 所以,在pandas中,字符串拼接的主要方法是使用`.str.cat()`。 其他可能的字符串拼接方法: - 使用Python的`+`操作符:例如`df['col1'] + df['col2']`。 - 使用`.apply()`配合lambda函数:`df['new_col'] = df.apply(lambda row: row['col1'] + row['col2'], axis=1)` - 使用`.str.join()`或其他字符串方法。 但根据引用,`.str.cat()`是专门设计用于拼接字符串列的常用方法。 回答结构: 1. **引言**:简要解释pandas中字符串拼接的重要性。 2. **主要方法**:详细介绍`.str.cat()`方法。 - 语法:例如`Series.str.cat(others=None, sep=None, na_rep=None)` - 参数解释:`others`可以是另一个Series或列表,`sep`是分隔符,`na_rep`用于处理NaN值。 - 示例:基于引用[^3],给出简单的示例。 3. **其他方法**:简要提及替代方案如使用`+`操作符或`.apply()`。 4. **注意事项**:讨论数据类型(确保是字符串类型),如引用[^3]中提到可能需要先转换为字符串。 5. **小结**:总结推荐方法。 6. **生成相关问题**:添加相关问题部分。 确保回答使用中文。 生成相关问题:至少三个,类似示例中的格式。 例如: 1. 如何处理字符串拼接中的缺失值(NaN)? 2. 如何使用分隔符拼接多个列? 3. 字符串拼接在数据清洗中的常见应用场景? 引用标识:在回答中引用段落末尾添加`[^引用号]`。用户提供了[^1], [^2], [^3],所以我需要在相关部分添加这些引用。 例如: - 在介绍`.str.cat()`时,引用[^1]和[^3]。 - 在提及其他字符串操作时,引用[^2]。 保持回答真实可靠:基于pandas官方文档。引用[^1]提到了Pandas官方文档链接,我可以暗示参考官方文档。 最终回答结构: - 标题或主题:Pandas中字符串拼接的方法。 - 正文: - 介绍。 - 方法1:使用`.str.cat()`。 - 方法2:使用`+`操作符。 - 方法3:其他方法(如`.apply()`)。 - 注意事项。 - 相关问题。 开始撰写回答。 </think>### Pandas中字符串拼接的方法 在数据分析中,字符串拼接是常见的数据处理任务,尤其在数据清洗和特征工程中至关重要。Pandas 提供了高效的内置方法来实现字符串拼接,确保代码简洁且高性能。以下我将基于用户查询和系统引用,详细介绍 Pandas 字符串拼接的核心方法、实现示例以及注意事项。引用内容主要来自站内文献,我会在相关段落末尾标注引用标识。 #### 1. **核心方法:使用 `.str.cat()`** `.str.cat()` 是 Pandas 专为字符串拼接设计的矢量化方法,适合处理量数据。它支持灵活的参数配置,包括分隔符和缺失值处理。 - **语法**: ``` Series.str.cat(others=None, sep=None, na_rep=None) ``` - `others`:要拼接的其他列或序列(可以是 Series、列表或单个字符串)。 - `sep`:拼接时使用的分隔符(可选,默认为空字符串)。 - `na_rep`:用于替换缺失值(NaN)的字符串(可选)。 - **实现示例**: 假设有一个 DataFrame `df`,包含两列字符串 `date` 和 `hour`。先将列转换为字符串类型(确保数据类型正确),然后使用 `.str.cat()` 拼接: ```python import pandas as pd # 创建示例 DataFrame df = pd.DataFrame({ 'date': ['2023-01-01', '2023-01-02'], 'hour': ['08:00', '12:00'] }) # 转换为字符串类型(避免类型错误) df['date'] = df['date'].astype('str') df['hour'] = df['hour'].astype('str') # 使用 .str.cat() 拼接,添加分隔符 '_' df['datetime'] = df['date'].str.cat(df['hour'], sep='_') print(df) ``` 输出: ``` date hour datetime 0 2023-01-01 08:00 2023-01-01_08:00 1 2023-01-02 12:00 2023-01-02_12:00 ``` 此方法高效且支持批处理,优于循环操作[^3]。 #### 2. **替代方法:使用 `+` 操作符或 `.apply()`** 如果数据量较小或需要简单拼接,可以使用 Python 内置操作符或函数,但性能不如 `.str.cat()`。 - **使用 `+` 操作符**: 直接对列进行加法操作,适用于无分隔符的简单拼接。 ```python df['datetime'] = df['date'] + df['hour'] # 输出 '2023-01-0108:00' ``` 注意:此方法不处理分隔符和缺失值,可能引入错误[^2]。 - **使用 `.apply()` 与 lambda 函数**: 灵活性高,支持复杂逻辑,但速度较慢。 ```python df['datetime'] = df.apply(lambda row: row['date'] + '_' + row['hour'], axis=1) ``` 适合少量数据处理,但不推荐用于型数据集[^2]。 #### 3. **注意事项** - **数据类型转换**:确保列是字符串类型后再拼接。使用 `astype('str')` 转换非字符串列(如数字或日期),避免错误[^3]。 - **处理缺失值**:在 `.str.cat()` 中指定 `na_rep` 参数替换 NaN,例如 `na_rep='Missing'`。 - **性能优化**:对于大数据集,`.str.cat()` 比循环或 `.apply()` 更快,因为它基于矢量化操作。参考官方文档优化代码[^1]。 - **多列拼接**:`.str.cat()` 支持拼接多个列(传递列表),例如 `df['col1'].str.cat([df['col2'], df['col3']], sep='-')`[^1]。 #### 总结 在 Pandas 中,推荐优先使用 `.str.cat()` 方法进行字符串拼接,因为它高效、灵活且易于维护。结合数据类型转换和参数配置,可以处理各种真实场景。如果您需要进一步优化或处理复杂案例,建议查阅 Pandas 官方文档[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值