久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

Java怎么實現字符串分隔

148次閱讀
沒有評論

共計 2196 個字符,預計需要花費 6 分鐘才能閱讀完成。

這篇文章主要介紹“Java 怎么實現字符串分隔”,在日常操作中,相信很多人在 Java 怎么實現字符串分隔問題上存在疑惑,丸趣 TV 小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Java 怎么實現字符串分隔”的疑惑有所幫助!接下來,請跟著丸趣 TV 小編一起來學習吧!

1、題目描述

連續輸入字符串,請按長度為 8 拆分每個字符串后輸出到新的字符串數組;

長度不是 8 整數倍的字符串請在后面補數字 0,空字符串不處理。

輸入描述:

連續輸入字符串 (輸入 2 次, 每個字符串長度小于 100)

輸出描述:

輸出到長度為 8 的新字符串數組

輸入例子:

abc
123456789

輸出例子:

abc00000
12345678
90000000

2、程序方案一

基本思路:

#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 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 i=i+1)
 cout str.substr(i*8,8) endl;
 if(last 0) cout str.substr(8*cir) fil.substr(last) endl;
}

到此,關于“Java 怎么實現字符串分隔”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注丸趣 TV 網站,丸趣 TV 小編會繼續努力為大家帶來更多實用的文章!

正文完
 
丸趣
版權聲明:本站原創文章,由 丸趣 2023-08-16發表,共計2196字。
轉載說明:除特殊說明外本站除技術相關以外文章皆由網絡搜集發布,轉載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 黑水县| 永善县| 晋江市| 旺苍县| 出国| 文成县| 左权县| 新乐市| 吉林市| 昭平县| 嘉祥县| 东平县| 永胜县| 余干县| 宁安市| 揭西县| 凌海市| 田东县| 酒泉市| 博野县| 东乡县| 贵阳市| 临洮县| 乌苏市| 麻阳| 杨浦区| 建德市| 含山县| 龙口市| 大丰市| 宁城县| 扶余县| 商洛市| 边坝县| 鲁山县| 垫江县| 潍坊市| 盐池县| 渑池县| 榆中县| 海宁市|