这篇文章主要介绍“Java怎么实现字符串分隔”,在日常操作中,相信很多人在Java怎么实现字符串分隔问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Java怎么实现字符串分隔”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
连续输入字符串,请按长度为8拆分每个字符串后输出到新的字符串数组;
长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。
输入描述:
连续输入字符串(输入2次,每个字符串长度小于100)
输出描述:
输出到长度为8的新字符串数组
输入例子:
abc 123456789
输出例子:
abc00000 12345678 90000000
基本思路:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
while(cin>>s){
int count = 0;
int i=0;
while(i<s.length()){
if(count<8){
//一开始执行这一句,因为我们的初值设置为count=0
cout<<s[i];
i++;
count++;
//直到输出8个数字为止
}
else
{
cout<<endl;
count = 0;
//如果满8位则换行,然后重新置count为0,再执行上面的输出
}
}
while(count<8){
cout<<0;
count++;
}
//最后一排的输出控制,如果不满8位补零输出
cout<<endl;
}
}
#include<iostream>
#include<string>
using namespace std;
void print(const char *p);
char str[9]={0};
int main(){
string str1,str2;
const char *p1,*p2;
getline(cin,str1);
getline(cin,str2);
p1 = str1.c_str();
p2 = str2.c_str();
/*
const char *c_str();
c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
*/
print(p1);
print(p2);
return 0;
}
void print(const char *p){
while(*p !='\0'){
//循环到字符串结束
int k=0;
while((k++) < 8){
//控制输出8位
str[k] = *p;
if(*p == '\0'){
str[k] = '0';
continue;
}
p++;
}
str[k] = '\0';
for(int i=0;i<8;i++)
cout << str[i];
cout<<endl;
}
}
基本思路:调用库函数substr()截取字符串。
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1;
string s2 = "0000000";
unsigned int i = 0;
while ( getline(cin, s1) )
{
for (i = 0; i+8 < s1.length(); i=i+8)
{
cout << s1.substr(i, 8) << endl;
}
if (s1.length() - i > 0)
{
cout << s1.substr(i, s1.length() - i) + s2.substr(0, 8-(s1.length() - i))<< endl;
}
}
return 0;
}
//getline遇到换行符,结束输入,进入while循环,利用string的substr函数取出字符串。
#include<iostream>
#include<string>
using namespace std;
void output(string str);
int main(){
string str1; string str2;
cin>>str1>>str2;
output(str1);
output(str2);
return 0;
}
void output(string str){
int cir=str.size()/8;
int last=str.size()%8;
string fil="00000000";
for(int i=0;i<cir;i=i+1)
cout<<str.substr(i*8,8)<<endl;
if(last>0) cout<<str.substr(8*cir)<<fil.substr(last)<<endl;
}
到此,关于“Java怎么实现字符串分隔”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/2312175/blog/667148