常见c语言字符串题

字符串是程序员求职笔试中必考题型,很能考查出编程的基础。下文选取了几个常见的考题和大家进行分享。

     1、编写函数,实现把一个char组成的字符串循环右移n位。如abcdehi,n=2。则输出hiabcde。

#include "iostream"
using namespace std;
 
const int MAX_LEN = 20;
void LoopMove(char* cpStr, int iSteps)
{
    //注意,在整个处理过程中,cpStr的最后字符都没有涉及处理
    char cTempArray[MAX_LEN];
    size_t szStrLength = strlen(cpStr);
    size_t in = szStrLength -iSteps;
    memcpy(cTempArray, cpStr + in, iSteps);
    memcpy(cTempArray + iSteps, cpStr, in);
    memcpy(cpStr, cTempArray, szStrLength);
    cTempArray[szStrLength + 1] = '\0';
    cout << cTempArray << endl;
}
 
int main() 
{
    char ctemp[] = "abcdefghi";
    LoopMove(ctemp, 2);
    cout << ctemp << endl;
    return 1;
}

2、输入一行字符串,找出其中出现的相同且长度最长的字符串,输出它及其首字符的位置。如yyabcdabjcabceg,则输出为abc,3。

 
  1. 大体思路:把字符串yyabcdabjcabceg拆解:  
  2. yyabcdabjcabceg  
  3. yabcdabjcabceg  
  4. abcdabjcabceg  
  5. ...  
  6. ceg  
  7. eg  
  8. g  
  9. 然后对字符串进行排序,比较相邻字符串的前驱,求最长的共公前驱。  
  10. 在我们的程序中的体现,我们没有用这种方法,因为这种方法在排序中会用很多时间。我们借用了C++的实现函数find来巧妙的实现。  
  11. 注:basic_string::substr  
  12. basic_string substr(size_type pos = 0, size_type n = npos) const;  
  13.     The member function returns an object whose controlled sequence is a copy of up to n elements of the controlled sequence beginning at position pos.  
  14. 返回一个从指定位置开始,并具有指定长度的子字符串。  
  15. 参数   
  16. pos 必选。所需的子字符串的起始位置。字符串中第一个字符的索引为 0。  
  17. n 可选项。返回的子字符串中包含的字符数。  
  18. 备注 如果 n 为 0 或负数,将返回一个空字符串。如果没有指定该参数,则子字符串将延续到字符串的结尾。  
  19.     在VS中测试,如是n是负数或大于主串的总长度,则输出是pos开始到主串末尾的字符。  
  20. 示例代码   
大体思路:把字符串yyabcdabjcabceg拆解:
yyabcdabjcabceg
yabcdabjcabceg
abcdabjcabceg
...
ceg
eg
g
然后对字符串进行排序,比较相邻字符串的前驱,求最长的共公前驱。
在我们的程序中的体现,我们没有用这种方法,因为这种方法在排序中会用很多时间。我们借用了C++的实现函数find来巧妙的实现。
注:basic_string::substr
basic_string substr(size_type pos = 0, size_type n = npos) const;
    The member function returns an object whose controlled sequence is a copy of up to n elements of the controlled sequence beginning at position pos.
返回一个从指定位置开始,并具有指定长度的子字符串。
参数 
pos 必选。所需的子字符串的起始位置。字符串中第一个字符的索引为 0。
n 可选项。返回的子字符串中包含的字符数。
备注 如果 n 为 0 或负数,将返回一个空字符串。如果没有指定该参数,则子字符串将延续到字符串的结尾。
    在VS中测试,如是n是负数或大于主串的总长度,则输出是pos开始到主串末尾的字符。
示例代码 
 
  1. #include "iostream"    
  2. #include "string"    
  3. using namespace std;     
  4. int main()    
  5. {   
  6.     string strInput;   
  7.     cout << "Input a string: " << endl;   
  8.     cin >> strInput;   
  9.     string strTemp;   
  10.     for (size_t i = strInput.length() - 1; i > 1; i--)   
  11.     {   
  12.         for (size_t j = 0; j < strInput.length(); j++)   
  13.         {   
  14.             if ((i + j) <= strInput.length())   
  15.             {   
  16.                 size_t szForw = 0;   
  17.                 size_t szBacw = 0;   
  18.                 strTemp = strInput.substr(j, i);   
  19.                 szForw = strInput.find(strTemp);   
  20.                 szBacw = strInput.rfind(strTemp);   
  21.                 if (szBacw != szForw)   
  22.                 {   
  23.                     cout << strTemp << " " << szForw + 1 << endl;   
  24.                     return 0;   
  25.                 }   
  26.             }   
  27.         }   
  28.     }   
  29.     
  30.     return 1;   
  31. }  
#include "iostream" 
#include "string" 
using namespace std;   
int main()  
{ 
    string strInput; 
    cout << "Input a string: " << endl; 
    cin >> strInput; 
    string strTemp; 
    for (size_t i = strInput.length() - 1; i > 1; i--) 
    { 
        for (size_t j = 0; j < strInput.length(); j++) 
        { 
            if ((i + j) <= strInput.length()) 
            { 
                size_t szForw = 0; 
                size_t szBacw = 0; 
                strTemp = strInput.substr(j, i); 
                szForw = strInput.find(strTemp); 
                szBacw = strInput.rfind(strTemp); 
                if (szBacw != szForw) 
                { 
                    cout << strTemp << " " << szForw + 1 << endl; 
                    return 0; 
                } 
            } 
        } 
    } 
  
    return 1; 
}
 
  1. 3、实现strstr()功能。如主串是12345678,子串是234,则返回2345678。  
3、实现strstr()功能。如主串是12345678,子串是234,则返回2345678。
 
  1. #include "iostream"    
  2. #include "string"    
  3. using namespace std;   
  4.     
  5. const char* strstr1(const char* strMainString, const char* strSubString)   
  6. {   
  7.     for (size_t i = 0; strMainString[i]; i++)   
  8.     {   
  9.         size_t iTempj = 0;   
  10.         size_t iTempi = i;   
  11.         if (strMainString[iTempi] == strSubString[iTempj])   
  12.         {   
  13.             while(strMainString[iTempi++] == strSubString[iTempj++])   
  14.             {   
  15.                 if (strSubString[iTempj] == '\0')   
  16.                     return &strMainString[i];   
  17.             }   
  18.         }   
  19.     }   
  20.     return NULL;   
  21. }   
  22.     
  23. int main()    
  24. {   
  25.     char str1[] = "12345678";   
  26.     char str2[] = "234";   
  27.     const char *str3 = strstr1(str1, str2);   
  28.     cout << str3 << endl;   
  29.     return 1;   
  30. }  
#include "iostream" 
#include "string" 
using namespace std; 
  
const char* strstr1(const char* strMainString, const char* strSubString) 
{ 
    for (size_t i = 0; strMainString[i]; i++) 
    { 
        size_t iTempj = 0; 
        size_t iTempi = i; 
        if (strMainString[iTempi] == strSubString[iTempj]) 
        { 
            while(strMainString[iTempi++] == strSubString[iTempj++]) 
            { 
                if (strSubString[iTempj] == '\0') 
                    return &strMainString[i]; 
            } 
        } 
    } 
    return NULL; 
} 
  
int main()  
{ 
    char str1[] = "12345678"; 
    char str2[] = "234"; 
    const char *str3 = strstr1(str1, str2); 
    cout << str3 << endl; 
    return 1; 
}

4、将一句话中的单词倒置,标点符号不倒换。如“i come from tianjin.”,倒换后变成“tianjin. from come i”。

  1. 大体思路:先把整个字符串调整,再针对每个单词进行调整。  
  2. 示例代码   
  3. view sourceprint?  
  4. #include "iostream"    
  5. #include "string"    
  6. //#include "functional"    
  7. //#include "algorithm"    
  8. using namespace std;   
  9.     
  10. int main()    
  11. {   
  12.     cout << "Input a string: " << endl;   
  13.     string strOfaLine;   
  14.     getline(cin, strOfaLine);      
  15.     size_t szStrLength = strOfaLine.length();   
  16.     size_t szTempbeg = 0;   
  17.     size_t szTempend = szStrLength - 1;   
  18.         
  19.     //第一步,全局交换    
  20.     while(szTempbeg < szTempend)   
  21.     {   
  22.         swap<char>(strOfaLine[szTempbeg++], strOfaLine[szTempend--]);   
  23.     }   
  24.     
  25.     //第二步,局部交换    
  26.     size_t szTempi = 0;   
  27.     while (strOfaLine[szTempi])   
  28.     {   
  29.         if (strOfaLine[szTempi] != ' ')   
  30.         {   
  31.             szTempbeg = szTempi;   
  32.             while(strOfaLine[szTempi] != '\0' && strOfaLine[szTempi] != ' ')   
  33.             {   
  34.                 szTempi++;   
  35.             }   
  36.             szTempi--;   
  37.             szTempend = szTempi;   
  38.         }   
  39.         while(szTempbeg < szTempend)   
  40.         {   
  41.             swap<char>(strOfaLine[szTempbeg++], strOfaLine[szTempend--]);   
  42.         }   
  43.         szTempi++;   
  44.     }   
  45.     cout << strOfaLine << endl;   
  46.     return 1;   
  47. }  
大体思路:先把整个字符串调整,再针对每个单词进行调整。
示例代码 
view sourceprint?
#include "iostream" 
#include "string" 
//#include "functional" 
//#include "algorithm" 
using namespace std; 
  
int main()  
{ 
    cout << "Input a string: " << endl; 
    string strOfaLine; 
    getline(cin, strOfaLine);    
    size_t szStrLength = strOfaLine.length(); 
    size_t szTempbeg = 0; 
    size_t szTempend = szStrLength - 1; 
      
    //第一步,全局交换 
    while(szTempbeg < szTempend) 
    { 
        swap<char>(strOfaLine[szTempbeg++], strOfaLine[szTempend--]); 
    } 
  
    //第二步,局部交换 
    size_t szTempi = 0; 
    while (strOfaLine[szTempi]) 
    { 
        if (strOfaLine[szTempi] != ' ') 
        { 
            szTempbeg = szTempi; 
            while(strOfaLine[szTempi] != '\0' && strOfaLine[szTempi] != ' ') 
            { 
                szTempi++; 
            } 
            szTempi--; 
            szTempend = szTempi; 
        } 
        while(szTempbeg < szTempend) 
        { 
            swap<char>(strOfaLine[szTempbeg++], strOfaLine[szTempend--]); 
        } 
        szTempi++; 
    } 
    cout << strOfaLine << endl; 
    return 1; 
}

5、找出字符串中最长最短单词并统计词数

  1. /*编写程序计算sentence中有多少个单词,并输出其中最长和最短的单词。 
  2. 如果有多个最长或最短的单词,则将其全部输出。 
  3. 其中 
  4. string line1="We were her pride of 10 she named us:"; 
  5. string line2="Benjamin,Phoenix,the Prodigal"; 
  6. string line3="and perspicacious pacific suzanne"; 
  7. string sentence = line1+' '+line2+' '+line3; 
  8. */  
  9.   
  10. #include "stdafx.h"   
  11. #include <vector>   
  12. #include <iostream>   
  13. #include <string>   
  14.   
  15. using namespace std;  
  16.   
  17. int main(int argc, char* argv[])  
  18. {  
  19.     string line1="We were her pride of 10 she named us:";  
  20.     string line2="Benjamin,Phoenix,the Prodigal";  
  21.     string line3="and perspicacious pacific suzanne";  
  22.     string sentence = line1+' '+line2+' '+line3;  
  23.     string separators(" \t;,\v\t\n\r\f");     
  24.     string word;  
  25.     vector<string>longestWord,shortestWord;  
  26.     string::size_type maxLen,minLen,wordLen,count=0;  
  27.     string::size_type start_pos=0,end_pos=0;  
  28.     while ((start_pos=sentence.find_first_not_of(separators,start_pos))!=string::npos)  
  29.     {  
  30.         ++count;  
  31.         end_pos = sentence.find_first_of(separators,start_pos);  
  32.         if(end_pos==string::npos)  
  33.         {  
  34.             wordLen = sentence.size()-start_pos;  
  35.         }  
  36.         else  
  37.         {  
  38.             wordLen = end_pos-start_pos;  
  39.         }  
  40.         word.assign(sentence.begin()+start_pos,sentence.begin()+start_pos+wordLen);  
  41.         start_pos=sentence.find_first_not_of(separators,end_pos);  
  42.         if(count==1)  
  43.         {  
  44.             minLen=maxLen=wordLen;  
  45.             longestWord.push_back(word);  
  46.             shortestWord.push_back(word);  
  47.         }  
  48.         else  
  49.         {  
  50.             if(wordLen>maxLen)  
  51.             {  
  52.                 maxLen = wordLen;  
  53.                 longestWord.clear();  
  54.                 longestWord.push_back(word);  
  55.             }  
  56.             else if (wordLen<minLen)  
  57.             {  
  58.                 minLen = wordLen;  
  59.                 shortestWord.clear();  
  60.                 shortestWord.push_back(word);  
  61.             }  
  62.             else if(wordLen==minLen)  
  63.             {  
  64.                 shortestWord.push_back(word);         
  65.             }  
  66.             else if(wordLen==maxLen)  
  67.                 longestWord.push_back(word);  
  68.         }  
  69.   
  70.     }  
  71.     cout<<"word count="<<count<<" words"<<endl;  
  72.     cout<<"longest words are:";  
  73.     for(vector<string>::iterator i=longestWord.begin();i!=longestWord.end();i++)  
  74.     {  
  75.         cout<<*i<<endl;  
  76.     }  
  77.     cout<<"shortest words are:";  
  78.     for(vector<string>::iterator j=shortestWord.begin();j!=shortestWord.end();j++)  
  79.     {  
  80.         cout<<*j<<endl;  
  81.         }     
  82.     return 0;  
  83. }  
/*编写程序计算sentence中有多少个单词,并输出其中最长和最短的单词。
如果有多个最长或最短的单词,则将其全部输出。
其中
string line1="We were her pride of 10 she named us:";
string line2="Benjamin,Phoenix,the Prodigal";
string line3="and perspicacious pacific suzanne";
string sentence = line1+' '+line2+' '+line3;
*/

#include "stdafx.h"
#include <vector>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
	string line1="We were her pride of 10 she named us:";
	string line2="Benjamin,Phoenix,the Prodigal";
	string line3="and perspicacious pacific suzanne";
	string sentence = line1+' '+line2+' '+line3;
	string separators(" \t;,\v\t\n\r\f");	
	string word;
	vector<string>longestWord,shortestWord;
	string::size_type maxLen,minLen,wordLen,count=0;
	string::size_type start_pos=0,end_pos=0;
	while ((start_pos=sentence.find_first_not_of(separators,start_pos))!=string::npos)
	{
		++count;
		end_pos = sentence.find_first_of(separators,start_pos);
		if(end_pos==string::npos)
		{
			wordLen = sentence.size()-start_pos;
		}
		else
		{
			wordLen = end_pos-start_pos;
		}
		word.assign(sentence.begin()+start_pos,sentence.begin()+start_pos+wordLen);
		start_pos=sentence.find_first_not_of(separators,end_pos);
		if(count==1)
		{
			minLen=maxLen=wordLen;
			longestWord.push_back(word);
			shortestWord.push_back(word);
		}
		else
		{
			if(wordLen>maxLen)
			{
				maxLen = wordLen;
				longestWord.clear();
				longestWord.push_back(word);
			}
			else if (wordLen<minLen)
			{
				minLen = wordLen;
				shortestWord.clear();
				shortestWord.push_back(word);
			}
			else if(wordLen==minLen)
			{
				shortestWord.push_back(word);		
			}
			else if(wordLen==maxLen)
				longestWord.push_back(word);
		}

	}
	cout<<"word count="<<count<<" words"<<endl;
	cout<<"longest words are:";
	for(vector<string>::iterator i=longestWord.begin();i!=longestWord.end();i++)
	{
		cout<<*i<<endl;
	}
	cout<<"shortest words are:";
	for(vector<string>::iterator j=shortestWord.begin();j!=shortestWord.end();j++)
	{
		cout<<*j<<endl;
		}	
	return 0;
}



 


 #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 30
/***********************************************
*函数名称: fun
*创建时间: 2010.12.5
*描    述: 对一个字符串重新排列,字母排在前面,数字排在后面,并不改变原来字母之间以及数字之间的字符顺序。
*参    数: char * s,int *m
*返 回 值: chLetter(数组chLetter[]的首元素地址)
*局部变量: char chLetter[N];
*   char chNumber[N];
*   int i,j,k;
************************************************/
char * fun(char * s,int *m)    //参数m是通过调试才想到的
{
 char chLetter[N]; //用来存放字母
 char chNumber[N]; //用来存放数字
 int i,j,k;
 i=0; //初始化
 j=0; //j用来记录字母的个数
 k=0; //k用来记录数字的个数
 for (i=0; i<N; i++)
 {
  if (s[i] >= 'A' && s[i] <= 'Z'   //将字母存入chLetter[]
   || s[i] >= 'a' && s[i] <= 'z')
  {
   chLetter[j]=s[i];
   j++;
  }
  if (s[i] >= '0' && s[i] <='9')   //将数字存入chNumber[]
  {
   chNumber[k]=s[i];
   k++;
  }
 }
 chLetter[j]='';
 chNumber[k]='';
 *m=j+k;          //用来返回最后输入和输出时字符的个数
 strcat(chLetter,chNumber);
 return chLetter;
}
//主函数
void main()
{
 char s[N];
 int i;
 int m; 
 char *p;
 p=NULL;
 printf("请输入字符串(30字符以内):n");
 scanf("%s",s);
 p=fun(s,&m);     //刚开始没定义出这个m来现限制指针p所指数组的长度就出现了后面两个字符乱码
 for (i=0; i<m; i++)    //将返回的值复制给数组以待输出
 {
  s[i]=p[i];
 }
 
 printf("结果为:");
 for (i=0; i<m; i++)    //输出结果
 {
  printf("%c",s[i]);
 }
 printf("n");
}


 

 

浮点数转换为字符串

#include "stdafx.h"
#include "stdlib.h"

char *F2S(double d, char* str)
{
  char str1[40];
  int j=0,k,i;
  i = (int)d;  //浮点数的整数部分
  //d = d-(int)d;
  while(i>0)
  {
    str1[j++] = i%10+'0';
    i /= 10;
  }
  for(k=0;k<j;k++)
    str[k] = str1[j-1-k]; //

  str[j++] = '.';
  d -= (int)d;
  for(i=0;i<10;i++)
  {
    d *= 10;
    str[j++] = (int)d+'0';
    d -= (int)d;
  }
  while(str[--j]=='0');
    str[++j] = '\0';
  return str;
}


int _tmain(int argc, _TCHAR* argv[])
{
    double d = 365.897003120000;
  char str[20];
  char *p = F2S(d, str);
  printf("%s\n",str);
  printf("%s\n",p);

  return 0;
}

 

 

posted @ 2012-09-16 17:16  hktkhhhh  阅读(7089)  评论(1编辑  收藏  举报