字符串的输入输出处理(c++,java)

题目描述

字符串的输入输出处理。

输入

第一行是一个正整数N,最大为100。之后是多行字符串(行数大于N), 每一行字符串可能含有空格,字符数不超过1000。

输出

先将输入中的前N行字符串(可能含有空格)原样输出,再将余下的字符串(不含有空格)以空格或回车分割依次按行输出。每行输出之间输出一个空行。

样例输入

2
www.dotcpp.com DOTCPP
A C M
D O T CPP

样例输出

www.dotcpp.com DOTCPP

A C M

D

O

T

CPP

对字符串的处理第一想到的是字符串的分割

中规中矩的按照空格分割字符串方法

c++代码 

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<string>

using namespace std;

int main() {
    char str[1001];
    char *p;
    char *delim=" ";
    int n;
    cin>>n;
    getchar();
    for(int i=0;i<n;i++){
        gets(str);
        cout<<str<<endl<<endl;
    }
    while(gets(str)){

        p=strtok(str,delim);//返回值是分割段的起点位置
        while(p){
            cout<<p<<endl<<endl;
            p=strtok(NULL,delim);//下一个未分割处的起始位置
        }

    }



    return 0;
}

用的是strtok(char[],char*),第一个参数是需要分割的字符串,第二个参数是分隔符

java

package lqtest;


import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.nextLine();
//先将前n行按原样输出
        for(int i = 0;i < n;i++){
            String str = sc.nextLine();
            System.out.println(str + "\n");
        }
//再将余下的字符串(不含有空格)以空格或回车分割依次按行输出。
        while(sc.hasNext()){
            String s = sc.next();
            System.out.println(s + "\n");
        }
    }
}

其他的方法

#include<iostream>
#include<algorithm>
#include<queue>
#include<stdio.h>
#include<cstring>
#include<string>
#include<ctype.h>
#include<stack>
#include<sstream>
using namespace std;

int main() {
    string str;
    int n;
    cin>>n;
    getchar();//如果不写的话geline接收到的第一个是空
    for(int i=0;i<n;i++){
        getline(cin,str);
        cout<<str<<endl<<endl;
    }
    while(cin>>str)
        cout<<str<<endl<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值