zoukankan      html  css  js  c++  java
  • 8、与字符串处理相关的几个程序

    1、转换字符串的输入格式为:原来字符串里的字符+该字符连续出现的个数,例如字符串:1233422222,转化为1121324125

        我们用sprintf来实现,类同printf

    #include "iostream"
    #include "string"
    using namespace std;
    
    int main() 
    {
    cout << "Enter the numbers: " << endl;
    string str;
    cin >> str;
    size_t ilength = str.length();
    int icount = 1;
    char cMyChar[50];
    cMyChar[0] = '\0';
    int k;
    for (k = 0; k < ilength - 1; k++)
    {
    if (str[k] == str[k + 1]) //预判断
    {
    icount++; //记录字符个数
    }
    else
    {
    sprintf(cMyChar + strlen(cMyChar), "%c%d", str[k], icount);
    icount = 1;
    }
    }
    
    if (str[k] == str[k - 1])
    ;
    else
    icount = 1;
    sprintf(cMyChar + strlen(cMyChar), "%c%d", str[k], icount);
    cout << cMyChar << endl;
    return 1;
    }
    

    2、整数转换成字符串

    #include "iostream"
    using namespace std;
    int main() 
    {
    	int iMyData;
    	cin >> iMyData;
    	char cToTransfer[56];
    	char cTemp[56];
    	int icount = 0; //标记位数
    	while(iMyData)
    	{
    		cTemp[icount++] = iMyData % 10 + '0';
    		iMyData = iMyData / 10;
    	}
    	cTemp[icount] = '\0';
    	cout << cTemp << endl;
    	icount--;
    	int j = icount, i = 0;
    	while(j >=0)
    	{
    		cToTransfer[i++] = cTemp[j--];
    	}
    	cToTransfer[i] = 0;
    	cout << cToTransfer << endl;
    	return 1;
    }
    

    3、字符串转换成整数

    #include "iostream"
    using namespace std;
    
    int main() 
    {
    	char iMyData[56];
    	cin >> iMyData;
    	int iToTransfer[56];
    	int cTemp[56];
    	int icount = 0; //标记位数
        int iSum = 0;
    	while(iMyData[icount])
    	{
    		iSum = iSum * 10 + iMyData[icount] - '0';
    		icount++;
    	}
    	cout << iSum << endl;
    	return 1;
    }
    
  • 相关阅读:
    springmvc返回视图或当api
    springmvc初始注解案例
    @RequestMapping的属性、缩写
    struts初始案例
    2020-3-5所思所想
    使用selenium学习
    spring链接数据库与事务等实际运用再加
    spring的aop
    ubuntu安装docker
    java内存区域和内存溢出异常
  • 原文地址:https://www.cnblogs.com/mydomain/p/2036002.html
Copyright © 2011-2022 走看看