计算字符串最后一个单词的长度,单词以空格隔开
自己的思路:
#include<iostream>
#include<string>
using namespace std;
int f(){
string s;
while(getline(cin,s)){
int cut = s.rfind(' ');
string s2 = s.substr(cut+1);
cout<<s2.length()<<endl;
}
return 0;
}
int main(){
f();
}
看了下别人的代码,发现了自己忽略了输入字符串中会出现末尾空格的情况,需要进行空格清除
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
while(getline(cin,s)){
int n=0,flag=1;
for(int i=s.length()-1;i>=0;--i){
if(flag && s[i]==' '){
continue;
}
else if(s[i]!=' '){
flag = 0;
++n;
}
else{
break;
}
}
cout << n << endl;
}
return 0;
}
或者使用动态数组vector
,克服了末尾输出为空格的问题
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(){
string input;
vector<string>arr;
while(cin>>input){
arr.push_back(input);
}
cout<<arr[arr.size()-1].length()<<endl;
return 0;
}
使用python
s = input().split(' ')
print(len(s[-1]))
连续字符串为8个长度的字符串数组
一开始的思路是字符串拼接再分割,后来写的时候测试用例并没有完全通过,查看输入输出才发现其实字符串们并不用拼接,每个字符进行的操作都是一致的,可以不仅限于两个字符串,多个字符串也是ok的;另一个点就是需要考虑到字符串输入为空的情况
#include <iostream>
#include<string>
using namespace std;
int main(){
string s;
while(getline(cin,s)){
while(s.size()>=8){
cout << s.substr(0,8) <<endl;
s=s.substr(8);
}
if(!s.empty()){
cout << s.append(8-s.size(),'0') << endl;
}
}
return 0;
}
网上思路看了下也差不多,有使用递归的,但还是感觉自己写的要简洁清晰点
接下来是python,第一次写的时候鬼使神差用strip()
,其实到后面还是要进行判断,遂放弃
def f(s):
while len(s) > 8:
print(s[:8])
s = s[8:]
if(len(s)!=0):
print(s + "0" * (8-len(s)))
a =input()
b =input()
f(a)
f(b)
这道题要是先输入字符串个数再加上要输入的字符串就好了
while True:
try:
n= int(input())
for i in range(n):
s = input()
while len(s)>8 :
print(s[:8])
s = s[8:]
if(len(s)!=0):
print(s + '0'*(8-len(s)))
except:
break
反转字符串
这道题使用直接使用reverse输出就完了
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string s;
getline(cin,s);
reverse(s.begin(),s.end());
cout<<s<<endl;
return 0;
}
或者反向循环
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin >> str;
for(int i = str.size()-1; i >=0;i--)
cout << str[i];
}
python么,一行解决
print(input()[::-1])