C/C++在不确定字输入符串长度情况下,对其进行存储和字符操作问题

在很多IT公司的编程笔试题中都会提到,输如长度未知的字符串以及整数数组进行各种操作,本文进行简单地归纳。

对于输入一行随意大小的(中间不含空格)字符串求其长度并输出指定位上字符,用C++可以编程为:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
int main()
{
	int len;
	string str;
	cin >> str; 

	len = str.size(); //也可以使用len = strlen(str.c_str()),不能使用strlen(str)或者sizeof,前者因为传入参数类型不符合无法通过编译,后者返回固定值32
	cout << str << " --长度:" << len <<  " --第三位:" << str[2] << endl;//输出第三个字符的引用值
	return 0;
}

(关于sizeof()为何为定值32,可参见博客https://www.cnblogs.com/wanghetao/archive/2012/04/04/2431760.html中作者详细解释),编辑和调试结:

或者,使用C语言的字符操作,将输入string对象直接转化为字符组数char[],即:

#include <iostream>
#include <string>
#include <cstring>

using namespace std;
int main()
{
	int len;
	string str;
	cin >> str; 
	const char *ch;
	len = strlen(str.c_str()); 
	ch = str.c_str();
	cout << str << " --长度:" << len <<  " --第三位:" << ch[2] << endl;
	return 0;
}

因为字符串长度未知,在得到len之前声明char字符数组时须声明为指针变量,另外由于str.c_str()是const char*类型,因此,这里的ch指针也必须声明为const char*。另一方面,数组也可以在得到长度之后声明为ch[len]。

对于输入一行随意大小的(中间包含空格)字符串(即换行符为字符串终止符号),可以考虑getline()函数:

string str;
getline(cin,str);

使用C语言对输入随意长度的字符串进行存储和指定位输出操作,可以编写程序:

#include <string.h>
#include <stdio.h>
#include <stdlib.h> 

int main()
{
	char *p;
	p=(char *)malloc(sizeof(char));
	scanf("%s",p);
	int len=strlen(p);
	char str[len];
	for(int i=0;i<len;i++){
		str[i]=*p;
		p++;
	}
	printf("%c\n",str[2]);
	return 0;
}

编译和调试结果:

第一次调试的程序中没有加入malloc()函数,显示存在段错误。这是因为在声明指针p之后,没有对其进行初始化,即p没有指向的内存地址,因此不能直接取其指向的地址存储字符串的首个字符。使用malloc()函数则可以获取动态内存地址,存储字符串,并且通过指针p依次访问字符串中每个字符,从而将字符串复制到字符数组中。

再例如:计算字符串最后一个单词的长度,单词以空格隔开。

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

int main(){
    int len,count = 0;
    string line;
    getline(cin,line); //将整行字符串(包含空格)存储到string对象中,再由结尾向前遍历,遇到第一个空格字符截止
    len = line.size();
    for(int i=len-1;i>=0;--i){
        if(line[i]==' '){
            break;
        }
        else{
             count++; //在遇到第一个空格之前,每遍历一个字符,计数加1
        }
    }
    cout << count << endl;
}

举例:写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。

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

int main(){
    string a;
    int len;
    cin >> a;
    string b=a;//先要对字符对象进行初始化
    len = a.size();
    for(int i=0;i<len;++i){ 
        b[len-i-1]=a[i];
    }
    cout << b;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34041083/article/details/81737209