首页 > 试题广场 >

截取字符串

[编程题]截取字符串
  • 热度指数:157005 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
输入一个字符串和一个整数 k ,截取字符串的前k个字符并输出

数据范围:字符串长度满足

输入描述:

1.输入待截取的字符串

2.输入一个正整数k,代表截取的长度



输出描述:

截取后的字符串

示例1

输入

abABCcDEF
6

输出

abABCc
示例2

输入

bdxPKBhih
6

输出

bdxPKB
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        String str;
        int num;

        while (in.hasNext()) {
            str=in.next();
            num=in.nextInt();
            char[] arr=str.toCharArray();
            int temp=0;
            int i=0;
            while (temp <num) {
                if (arr[i] > 128) {
                    temp+=2;
                    if (temp<=num)
                        i++;
                }else {
                    temp++;
                    if (temp<=num)
                        i++;
                }
            }
            System.out.println(str.substring(0,i));

        }

        in.close();
    }
}

发表于 2017-07-18 14:26:20 回复(3)

python解法,非常简单


while True:
    try:
        a,b=input().split()
        print(a[:int(b)])


    except:
        break
发表于 2017-10-04 17:26:09 回复(17)
import java.util.*;
 
public class Main{
    public static void main(String[] args){
 		Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String s = in.next();
            int n = in.nextInt();
            StringBuilder sb = new StringBuilder();
            for(int i=0,len=0;i<s.length() && len<n;i++){
            	char c = s.charAt(i);
            	if((int)c>255){
            		if((len+2)>n)
            			break;
            		len+=2;
            		sb.append(c);
            	}
            	if((int)c>=0 && (int)c<=255){
            		len++;
					sb.append(c);
				}
            }
			System.out.println(sb.toString());
        }
        in.close();
    }
}

发表于 2016-04-06 21:53:51 回复(1)
/*****
貌似<string>自身就包含了这个功能,直接按截取长度输出,
若是截取边界正好卡在中文的字节处,则自动不输出中文
****/
#include<iostream>
#include<string>
using namespace std;
 
int main(){
    string str;
    while(cin>>str){
        int bit  =0;
        cin>>bit;         
        for(int j =0;j<bit;++j)
            cout<<str[j];
        cout<<endl;
    }     
    return 0;
}

发表于 2016-08-19 16:49:08 回复(1)
python切片
print(input()[0:int(input())])


发表于 2022-03-14 23:43:09 回复(0)
牛客能不能规范一点,java中,一个汉字 UTF-8是三个字节, GBK是两个字节两个
发表于 2016-08-30 23:13:52 回复(0)
利用 ch>>8 != 0 判别是否汉字
发表于 2019-07-13 18:04:59 回复(0)
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    int N;
    while(cin>>s>>N){
        string ss;
        if(s[N-1]>=128)//判断尾字符是否是汉子的前一个字节
        	ss=s.substr(0,N-1);
        else
            ss=s.substr(0,N);
        cout<<ss<<endl;    
    }
    return 0;
}

发表于 2016-07-20 10:08:44 回复(0)
我ABC汉DEF
6
这样的输入不是应该是两行输入吗?为什么是用split(" ")?
发表于 2020-07-23 22:13:59 回复(2)
解题思路:
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)
const str = readline()
console.log(str.substring(0,readline()))

发表于 2022-06-13 21:21:17 回复(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)
我喜欢这种不用动脑的题
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    while(cin>>str)
    {
        int n;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cout<<str[i];
        }
        cout<<endl;
    }
    return 0;
}

发表于 2020-11-20 22:32:40 回复(1)
我靠,这道题有病吧,样例输入为两行,实际上为一行。
发表于 2020-10-18 16:40:16 回复(0)
我的思路
首先是对字符串转化为字符数组,char[] chars
再一一对每一个字符进行判断,不在'A'~'Z'和'a' ~'z'之间的 我就count = count+2;判断结束条件为,count<num-1  y因为汉字的占据两个字符(题目的测试用例还是不多的。我刚把我的代码改了 count<num,也是可以通过的),请大家批评指正
在里面这个行列的我就count++;然后进行判断,count<=num,采用了一个StringBuiler对象进行append
import java.util.Scanner;

/**
 * 按字节截取字符串
 *
 * 编写一个截取字符串的函数,输入为一个字符串和字节数,
 * 输出为按字节截取的字符串。但是要保证汉字不被截半个,
 * 如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF"6,
 * 应该输出为"我ABC"而不是"我ABC+汉的半个"。
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String s = sc.next();
            int num = sc.nextInt();
            System.out.println(interceptString(s,num));
        }
    }

    /**
     * 返回截取后的字符串
     * @param s  输入的字符串
     * @param num  字节数
     * @return
     */
    public static String interceptString(String s,int num){
        if(s == null||s.length()<=0){
            return null;
        }

        if(num <=0){
            return s;
        }

        char[] chars = s.toCharArray();
        int count = 0;
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<chars.length;i++){
            char c = chars[i];
            if((c>='A'&& c<='Z')||(c>='a'&&c<='z')){
                count++;
                if(count <= num){
                    sb.append(c);
                }
            }else{
                count = count +2;
                if(count < num -1){
                    sb.append(c);
                }
            }
           if(count >=num){
               break;
           }
        }
        return sb.toString();
    }
}


发表于 2020-09-28 17:18:05 回复(0)