首页 > 试题广场 >

截取字符串

[编程题]截取字符串
  • 热度指数:175570 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}对于给定的字符串 s 和整数 k,截取字符串 s 的前 k 个字符后输出。

输入描述:
\hspace{15pt}第一行输入一个长度为 1 \leqq {\rm len}(s) \leqq 10^3 、由小写字母和大写字母混合构成的字符串 s
\hspace{15pt}第二行输入一个整数 k \left(1 \leqq k \leqq {\rm len}(s)\right) 代表截取字符串的长度。


输出描述:
\hspace{15pt}输出一个长度为 k 的字符串,表示截取字符串 s 的前 k 个字符。
示例1

输入

NowCoderHello
8

输出

NowCoder
示例2

输入

abABCcDEF
6

输出

abABCc
解题思路:
1.首先读取字符串,注意使用getline(cin,str,' '),表示遇到空字符时读取字符串结束,为后续数字读入做准备,读取截取的字符长度n
2.循环输出,注意判断最后一个字符str[n-1]>0x80是否成立,若成立不输出,否则输出最后一个字符。

C++代码实现:
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    int n;
    while(getline(cin,str,' '))
    {
        cin>>n;
        cin.get();
        for(int i=0;i<n;i++)
        {
            if(str[i]>128 && (i==n-1))
            {
                continue;
            }
            cout<<str[i];
        }
        cout<<endl;
    }
    return 0;
}
发表于 2019-08-22 17:45:05 回复(0)
while True:
    try:
        ls=list(raw_input().split())
        s=ls[0]
        x=int(ls[1])
        ss=""
        m=0
        for i in s:
            #print(i)
            if ord(i)>128:
                m=m+2
                if m-1==x:
                    print(ss)
                    break
                ss=ss+i
            elif ord(i)<=128:
                m=m+1
                ss=ss+i
                if m==x:
                    print(ss)
                    break
    except:
        break

发表于 2019-07-23 20:44:59 回复(1)
import java.util.Scanner;
public class abc{
    public static void getResult(int N,String str){
        char[] temp=str.toCharArray();
        int count=0;
        int i=0;
        for(int j=0;j<str.length()&&count<N;j++){
        	if(temp[j]>128){
        		count+=2;
        	}else{
        		count++;
        	}
        }
        System.out.println(str.substring(0,count));
    }
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String str=sc.next();
            int N=sc.nextInt();
            getResult(N,str);
        }
        sc.close();
    }
}

发表于 2017-08-20 14:41:27 回复(2)
#include<iostream>
#include<string>
using namespace std;
//还是吐槽输入,到底是str和count一行输入还是两行分开,神烦
int main() {
	string str;
	while (cin>>str) {
		int len = 0, count = 0;
		cin >> len;
		string res;
		for (unsigned i = 0; i < str.size(); i++) {
			if (str[i] < 0 && str[i + 1] < 0) {
				if (count + 2 > len) break;
				count += 1;
				res += str[i], res += str[i + 1];
				i++;
			}
			else res += str[i];
			if (++count == len) break;
		}
		cout << res << endl;
	}
}

发表于 2017-03-16 23:22:08 回复(1)
s = gets.strip
n = gets.to_i 
puts s[0..(n-1)]

发表于 2022-06-17 00:20:23 回复(0)
希望能帮到一些同学
这题对于理解Scanner与空白符的关系很有帮助,
明白什么是空白符,以及next(),nextLine()之间的区别就简单了
下面是测试代码
import java.util.Scanner;
public class Main{
    public static void main(String[] arg){
        Scanner sc = new Scanner(System.in);
        System.out.println("遇见sc.next()开始第一次输入" );
//       这里,“首次”无论输入多少个空白符(空格、换行符(按回车)、制表符(tab键盘)都不会结束输入,
//       (即跳过首段连续的空白符)
//       直到读取到想要的字符串后,读到输入的空白符表示当前输入结束
//        (按了空格看起来没结束输入?当你按了回车,即换行符后程序才会将当前行输入的内容提交,然后继续执行)
        String str = sc.next();
        System.out.println("str = " + str);
        System.out.println("sc.nextInt()开始第二次输入");
//      获取到到上次sc.next()行尾的空白符
//      一样跳过首段空白
        int a = sc.nextInt();
        System.out.println("a = " + a);
//       nextLine(),不跳过首段空白
//       表示会受到sc.nextInt()遗留的空白符影响
//       如果想消除,两种办法
//       1.可以写两次sc.nextLine();第一个用来消除遗留的空白符(连续的空白符一齐消掉),第二个接收下一个数据
//       2.以"asdasd 2 asdasd"的方式输入(第二个不妨输入一段连续的空白符试试),即空格作为第一次输入结束结束
        String sr = sc.nextLine();
        System.out.println("sr = " + sr+"测试sr");
//        String sr2 = sc.nextLine();
//        System.out.println("sr = " + sr2+"测试sr2");
        char[] arr = str.toCharArray();
        for(int i=0;i<a;i++){
            System.out.print(arr[i]);
        }
    }
}



发表于 2022-06-16 02:41:46 回复(0)
package main
import "fmt"
func main() {
	input, n := "", 0
	fmt.Scanln(&input)
	fmt.Scanln(&n)
	fmt.Println(input[:n])
}

发表于 2022-06-03 15:04:17 回复(0)
我靠,这道题有病吧,样例输入为两行,实际上为一行。
发表于 2020-10-18 16:40:16 回复(0)
题目不难,主要是题干描述与实际执行用例不符。用例执行时字符串和长度是在同一行,注意这点就行。
import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()) {
            String input = sc.nextLine();
            String str = input.split(" ")[0];

            int num = Integer.parseInt(input.split(" ")[1]);

            int end = 0;

            for (int i = 0; i < str.length(); i++) {
                char a = str.charAt(i);
                if (19968 <= a && a <40869) {   // 汉字ASCII码范围
                    end += 2;
                } else {
                    end++;
                }
                if (end == num) {
                    System.out.println(str.substring(0, i+1));
                    break;
                } else if (end > num) {
                    System.out.println(str.substring(0, i));
                    break;
                } else {
                    continue;
                }
            }
        }
    }
}


编辑于 2020-09-05 13:04:12 回复(0)
#include <bits/stdc++.h>
using namespace std;
void fun(string str,int N){
    for(int i=0;i<N;i++)
        cout<<str[i];
    cout<<endl;
}
int main(){
    string a;
    int n;
    while(cin>>a){
        cin>>n;
        int sum=0;
        if(a[n-1]<0){
            for(int i=0;i<n;i++){
                if(a[i]<0)
                    sum++;
            }
            if(sum%2)
                fun(a,n-1);
            else
                fun(a,n);
        }
        else
            fun(a,n);
    }
    return 0;
}


发表于 2020-08-16 17:13:19 回复(0)
来个c语言版本的吧
#include <stdio.h>
#include <string.h>

int main(){
    char str[1024];
    while(scanf("%s", str) != EOF){
        int catLen, i, acLen;
        scanf("%d", &catLen);
        
        acLen = catLen;
        
        for(i = 0; i < catLen; i++){
            if(str[i] < 0){
                if(i+1 < catLen){
                    i+=1;
                }else {
                    acLen = i;
                    break;
                }
            }
        }
        str[acLen] = '\0';
        printf("%s\n", str);
    }
    
    return 0;
}

编辑于 2020-07-19 21:19:28 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            String str=sc.next();
            char[] ch=str.toCharArray();
            int num=sc.nextInt();
            int i=0;
            while(num>0){
                if(ch[i]>128){
                    num-=2;
                    i++;
                }
                else{
                    num--;
                    i++;
                }
            }
        System.out.println(str.substring(0,i));
        }
    }
}

发表于 2020-06-02 22:27:57 回复(0)
while True:
    try:
        s,n = input().split()
        n = int(n)
        res = ''
        for i in range(n):
            if n == 0:
                break
            elif n == 1 and not 'A'<= s[i] <='Z' and not 'a'<= s[i] <='z':
                break
            elif 'A'<= s[i] <='Z':
                res += s[i]
                n -= 1
            elif 'a'<= s[i] <='z':
                res += s[i]
                n -= 1
            else:
                res += s[i]
                n -= 2
        print(res)
    except:
        break
发表于 2020-05-10 22:51:48 回复(0)
while True:
    try:
        string , n = input().strip().split()
        result = ''
        a = 0
        for i in string:
            a += len(i.encode('gbk'))
            if a <= int(n):        #以例题为例,当i等于‘汉’,a已经等于7了,退出循环了,result= ‘我ABC’,加不上‘汉’了。
                result += i

        print(result)
    except:
        break

发表于 2020-03-27 15:42:20 回复(0)
while True:
    try:
        a,b = input().split()
        c,d = 0,[]
        for i in a:
            if c < int(b):
                if ord(i) > 128:
                    c += 2
                else:
                    c += 1
                d.append(i)
            elif c == int(b):
              break
            else:
              d.pop()
              break
        print("".join(d))
    except:
        break

发表于 2020-02-20 12:18:29 回复(0)

按字节数来新建字符串即可,解码不成功会得到一个特殊字符。比较坑的地方是输入数据是同一行的,跟样例不同(习惯了。

import java.io.BufferedInputStream;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner scanner = new Scanner(new BufferedInputStream(System.in));
        try{
            while (scanner.hasNext()) {
                byte[] bytes = scanner.next().getBytes();
                int n = Integer.parseInt(scanner.next());
                if (n > bytes.length)
                    n = bytes.length;
                if(n<0){
                    n=0;
                }
                String string = new String(bytes, 0, n);
                if (string.length() > 0 && string.charAt(string.length() - 1) == '�')
                    string = string.substring(0, string.length() - 1);
                System.out.println(string);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}
发表于 2019-07-28 01:25:53 回复(0)
#include <iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    string temp="";
    int n;
    while(cin>>str>>n)
    {
        if((str[n-1]&0x80)&&(str[n]&0x80))
        {
            for(int i=0;i<n-1;i++)
                 temp=temp+str[i];
        cout<<temp;
        }
        else
        {
            for(int i=0;i<n;i++)
                temp=temp+str[i];
        cout<<temp;
        }
        cout<<endl;
        temp.clear();
    }
    system("pause");
    return 0;
}
发表于 2019-04-16 20:25:23 回复(0)
try:
    while True:
        string,num = input().split()
        num = int(num)
        index = 0
        for i in string:
            if '\u4e00' <= i <= '\u9fff':
                if num >= 2:
                    index += 1
                    num -= 2
                else:
                    num = 0
            else:
                index += 1
                num -= 1
            if num == 0:
                break
        print(string[:index])

except Exception:
    pass
编辑于 2018-11-06 19:15:32 回复(0)
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String line = sc.next();
            int n = sc.nextInt();
            for(int i=0; i<line.length(); i++) {
                if(line.charAt(i)>'z') {
                    n--;
                }
            }
            System.out.println(line.substring(0, n));
        }
    }
}

发表于 2018-10-05 18:19:31 回复(1)
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;

public class Main{
    
    //4.编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
    //但是要保证汉字不被截半个,如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF"6,
    //应该输出为"我ABC"而不是"我ABC+汉的半个"。 
    //思路:判断有几个汉字,几个其他字符,将汉字变成两个,如:我我试试人人123
    //然后截取完以后还原(如果当前文章字符和下一个一样则截掉)
    public static String substringStr(String str,int index) {
        //拼接字符串         String result = "";
        if(str!=null&&!str.equals("")&&index>=0&&index<=str.getBytes().length) {
            String temp = "";
            //正则表达式判断字符是否中文             String regex = "[\\u4E00-\\u9FA5]";
            for(int i=0;i<str.length();i++) {
                if(String.valueOf(str.charAt(i)).matches(regex)) {
                    temp = temp + str.charAt(i) + str.charAt(i);
                }else {
                    temp = temp + str.charAt(i);
                }
            }
            //判断索引index位置上的数值是汉字还是其他类型
            //汉字而且不是全部截取
            if(String.valueOf(temp.charAt(index-1)).matches(regex)&&index<temp.length()) {
                if(temp.charAt(index-1)==temp.charAt(index)) {
                    temp = temp.substring(0, index-1);
                }else {
                    temp = temp.substring(0, index);
                }
            //非汉字
            }else {
                temp = temp.substring(0, index);
            }
                         List<Character> resultList = new ArrayList<Character>();
            for(int i=0;i<temp.length();i++) {
                if(i<temp.length()-1) {
                    //是汉字
                    if(String.valueOf(temp.charAt(i)).matches(regex)&&temp.charAt(i)==temp.charAt(i+1)) {
                        resultList.add(temp.charAt(i));
                        //跳过下一个
                        i++;
                    }else {
                        //不是汉字直接添加
                        resultList.add(temp.charAt(i));
                    }
                }else {
                    resultList.add(temp.charAt(i));
                }
            }
            Object[] obj = resultList.toArray();
            for(int i=0;i<obj.length;i++) {
                result += obj[i];
            }
            System.out.println(result);
        }
                 return result;
    }
         public static void main(String[] args) {                  Scanner sc = new Scanner(System.in);         while(sc.hasNext()) {             String str = sc.nextLine();             String[] split = str.split(" ");             int index = Integer.parseInt(split[1]);             String result= substringStr(split[0],index);         }          }
    
    
}

发表于 2018-07-03 15:52:47 回复(2)