首页 > 试题广场 >

字符串提取

[编程题]字符串提取
  • 热度指数:1664 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 128M,其他语言256M
  • 算法知识视频讲解
请从字符串中提取以最后一个[img]开头、以最后一个[\img]结尾的字符串,未找到匹配的字符串返回"null"

输入描述:
可能包含[img][\img]的字符串


输出描述:
截取后的字符串
示例1

输入

bbb[img]ccc[img]ddd[\img]eee[\img]

输出

[img]ddd[\img]eee[\img]
示例2

输入

abc

输出

null
字符串里面的 \ 要注意一下
发表于 2019-02-19 11:32:39 回复(0)
python操作字符串还是很方便的
s = input()
# 先分割字符串
lst_first = s.split('[')
lst_final = []
for item in lst_first:
    lst_final.extend(item.split(']'))
# 然后倒序遍历,获得[img]和[\img]封闭的范围后返回
res = []
flag = False
for i in range(len(lst_final) - 1, -1, -1):
    if lst_final[i] == "\img":
        res.append("[\img]")
        flag = True
    if flag and lst_final[i] == "img":
        res.append("[img]")
        flag = False
        break
    elif flag and (lst_final[i] not in ["img", "\img"]):
        res.append(lst_final[i])
if not flag:
    # 如果有[img]则结果正常,进行打印
    print("".join(res[::-1]))
else:
    # 否则并没有匹配到符合题意的字符串
    print("null")


发表于 2020-12-02 15:29:49 回复(0)
解题思路:
1.读入字符串str,定义beg,end两个整形变量用于存储字符串出现中[img]和[\img]的位置,初始化end=beg=0;
2.循环搜索字符串中是否存在字串[img]和[\img],如果存在,则更新end和beg的数值;
3.若beg,end中至少有有一个为0,或者end<beg成立,则输出null,否则输出str[beg-end+6]。

C++代码实现:
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    while(getline(cin,str))
    {
        int beg=0,end=0;
        int len=0;
        while(str[++len]);
        int i;
        for(i=0;i<len-5;i++){
            if(str[i]=='['&& str[i+1]=='i'&&str[i+2]=='m'&& str[i+3]=='g'&&str[i+4]==']'){
                beg=i;
            }
        }
        for(i=0;i<len-6;i++){
            if(str[i]=='['&& str[i+1]=='\\'&&str[i+2]=='i'&&str[i+3]=='m'&& str[i+4]=='g'&&str[i+5]==']'){
                end=i;
            }
        }
        if(beg==0 || beg==0 || beg>end){
            cout<<"null"<<endl;
        }
        else if(beg<end){
            for(i=beg;i<end+6;i++){
                cout<<str[i];
            }
            cout<<endl;
        }
    }
    return 0;
}
发表于 2019-09-12 22:03:58 回复(0)
python3
# 正则表达式,python环视需要限定匹配的字符个数,不能很好的解决这个问题
# 但这个字符串整体倒过来,都是在遇到第一个字符的时候匹配,然后在倒回来就可以了
# 注意字符串倒置,匹配的时候匹配的是]gmi\[而不是原字符

ss = input()[::-1]
r = ss.find(']gmi\[')
l = ss.find(']gmi[')
if r == -1 or l == -1 or r > l:
    print("null")
else:
    print(ss[r:l+5][::-1])# 字符串的来回倒置,容易弄混,另外注意加上查找串的长度


发表于 2019-08-22 00:03:54 回复(0)
#include <bits/stdc++.h>
using namespace std; 
int main()
{
    string s,res="";
    cin>>s;
    int m=-1,n=s.size();
    for(int i=s.size()-1;i>=0;i--)
    {
        if(s[i]==']')
        {
            string st="";
            for(int j=i-5;j<=i;j++)
                st+=s[j];
            if(st=="[\\img]")
            {
                n=i;
                break;
            }
        }
    }
    for(int i=n-1;i>=0;i--)
    {
        if(s[i]==']')
        {
            string st="";
            for(int j=i-4;j<=i;j++)
                st+=s[j];
            if(st=="[img]")
            {
                m=i-4;
                break;
            }
        }
    }
    if(m==-1||n==s.size())
        cout<<"null"<<endl;
    else
    {
        for(int i=m;i<=n;i++)
            cout<<s[i];
        cout<<endl;
    }
    return 0;
}

发表于 2019-06-18 15:37:04 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string str;
    while(getline(cin,str))
    {
        int len = str.length();
        int i = str.rfind("[img]",len-1);     //最后一个[img]的'['所在下标
        int j = str.rfind("[\\img]",len-1) + 5;   //最后一个[\img]的']'所在下标
        if(i < j)    // 可能出现\img前面没有img的情况
        {
            cout << str.substr(i,j-i+1) << endl;   //从第一个[img]开始截取(j-i+1)个长度的子字符串
        }
        else   //未找到匹配的字符串则返回"null"
        {
            cout << "null" << endl;
        }
    }
    return 0;
}

编辑于 2019-04-27 13:52:13 回复(0)
import java.util.*;
import java.lang.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String in = sc.nextLine();
        int e = in.lastIndexOf("[\\img]");
        int b = in.lastIndexOf("[img]");
        String result;
        if (b > 0 && e > 0 && b < e) { result = in.substring(b, e) + "[\\img]"; }
        else { result = "null"; }
        System.out.println(result);
    }
}
发表于 2019-02-15 10:52:16 回复(0)
package main

import (
    "fmt"
    "strings"
)

func main() {
    var s string
    fmt.Scan(&s)
    idx1:=strings.LastIndex(s,"[img]")
    idx2:=strings.LastIndex(s,"[\\img]")
    if idx1==-1||idx2==-1||idx1>idx2{
        fmt.Print("null")
    }else{
        fmt.Print(s[idx1:idx2+6])
    }
}

发表于 2023-03-21 09:52:08 回复(0)
import java.util.*;
public class Main {
    // 抖个机灵
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();
        String[] ss = s.split("\\[img]");
        String res = ss[ss.length-1];
        int idx = res.lastIndexOf("[\\img]");
        if (idx != -1) System.out.println("[img]" + res.substring(0, idx+6));
        else System.out.println("null");
    }
}
发表于 2022-07-26 20:33:55 回复(0)
#include <stdio.h>
#include <string.h>
char* substr(char *str, int left, int right)
{
    char *temp = (char *) malloc((right - left) * sizeof(char));
    for (int i = left; i < right; ++i) {
        temp[i - left] = str[i];
    }
    temp[right - left] = '\0';
    return temp;
}

int match(char *str, int pos)
{
    char *s1 = "[img]";
    char *s2 = "[\\img]";
    if (strlen(str) - pos >= 5 && strncmp(str + pos, s1, strlen(s1)) == 0) {
        return 1;
    } else if (strlen(str) - pos >= 6 && strncmp(str + pos, s2, strlen(s2)) == 0) {
        return -1;
    } else {
        return 0;
    }
}
int main()
{
    char str[100];
    scanf("%s", str);
    int begin, end;
    begin = end = -1;
    int left, right;
    left = right = 0;
    for (int i = strlen(str) - 5; i >= 0; --i) {
        if (!left && match(str, i) == 1) {
            begin = i;
            left = 1;
        } else if (!right && match(str, i) == -1) {
            end = i;
            right = 1;
        }
    }
    if (begin == -1 || end == -1 || begin >= end) {
        printf("null");
    } else {
        char *ptr = substr(str, begin, end + 6);
        printf("%s", ptr);
        free(ptr);
    }
    return 0;
}

发表于 2020-07-15 20:31:55 回复(0)
import java.util.Scanner;
public class Main{
    public static void main(String args[]){
       String s = new Scanner(System.in).nextLine();
        String sReverse = new StringBuilder(s).reverse().toString();
        int begin = -1, end = -1;
        begin = sReverse.indexOf("]gmi\\[");
        end = sReverse.indexOf("]gmi[");
        if (begin < end) {
            String s1 = sReverse.substring(begin, end +5);
            System.out.println(new StringBuilder(s1).reverse().toString());
        }else System.out.println("null");
    }
}

发表于 2020-06-06 19:28:38 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main()
{
	string s;
	cin >> s;
	int l = 0, r = 0;
	char* c = new char[s.size()];
	for (int i = 0; i < s.size(); i++)c[i] = s[i];
	for (int i = 0; i < s.size() - 4; i++)if (c[i] == '['&&c[i + 1] == 'i'&&c[i + 2] == 'm'&&c[i + 3] == 'g'&&c[i + 4] == ']')l = i;
	for (int i = 0; i < s.size() - 5; i++)if (c[i] == '['&&c[i + 1] == '\\'&&c[i + 2] == 'i'&&c[i + 3] == 'm'&&c[i + 4] == 'g'&&c[i + 5] == ']')r = i;
	if (l < r&&l != 0 && r != 0)for (int i = l; i < r + 6; i++)cout << s[i];
	else cout << "null";
}

发表于 2020-04-28 14:08:16 回复(0)
            string input = string.Empty;
            while (!string.IsNullOrEmpty(input = Console.ReadLine()))
            {
                int imgIndex = input.LastIndexOf("[img]");
                int imgIndex2 = input.LastIndexOf(@"[\img]");
                if (imgIndex == -1 || imgIndex2 == -1)
                {
                    Console.WriteLine("null");
                }
                else
                {
                    int end = imgIndex2 + @"[\img]".Length - imgIndex;
                    if (imgIndex > end)
                    {
                        Console.WriteLine("null");
                    }
                    else
                    {
                        string output = input.Substring(imgIndex, imgIndex2 + 6 - imgIndex);
                        Console.WriteLine(output);
                    }
                }
            }

发表于 2020-01-09 09:41:22 回复(0)
将原字符串倒过来,然后就是查找第一个以‘]gmi\[’开头,并且是首个‘]gmi[’ 结尾的字符串。这里我是自己实现了 find的功能,大家看看就好。
def solve(s):
    new = s[::-1]
    i = 0
    stack = []
    while i<len(s) and not stack:
        if new[i]==']' and i+6<len(s) and new[i:i+6]==']gmi\[':
            i += 6
            while i<len(s):
                if new[i]==']' and i+5<len(s) and new[i:i+5]==']gmi[':
                    break
                stack.append(new[i])
                i += 1
        i += 1
    if i<len(s):
        return '[img]'+''.join(stack)[::-1]+'[\img]'
    return 'null'
if __name__=='__main__':
    s = raw_input().strip()
    print solve(s)


发表于 2019-09-11 09:36:34 回复(0)
s=input()
ans=[]
for i in range(len(s)-5):
    if s[i]+s[i+1]+s[i+2]+s[i+3]+s[i+4]=='[img]':
        p0=i
    if s[i]+s[i+1]+s[i+2]+s[i+3]+s[i+4]+s[i+5]=='[\img]':
        p1=i

if len(s[p0:p1])==0:
    print('null')
else:
    print(s[p0:p1+6])

发表于 2019-05-12 15:27:37 回复(0)
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
    string str;
    cin>>str;
    int len=str.length();
    int flag_start=0,flag_end=0,start_ad,end_ad;
    for(int i=0;i<len-5;i++)
    {
        if(str.substr(i,5)=="[img]")
        {
            flag_start=1;
            start_ad=i;
        }
    }
    for(int i=0;i<len-6;i++)
    {
        if(str.substr(i,6)=="[\\img]")
        {
            flag_end=1;
            end_ad=i;
        }
    }
    if((flag_start==0||flag_end==0)||end_ad<start_ad)
    {
        cout<<"null"<<endl;
        return 0;
    }
    else
    {
        cout<<str.substr(start_ad,end_ad-start_ad+6)<<endl;
    }
    return 0;
}
关键在于对结尾判断时,反斜杠要输入两次
发表于 2019-04-18 17:28:23 回复(0)
str=input()
temp=True while(len(str) and temp): if('[img]'in str[1:]):
        str=str[1:] else:
        temp=False while(not str.endswith(r'[\img]') and len(str)):
    str=str[:-1] if(str): print(str) else: print('null')


发表于 2019-03-26 19:14:06 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();

        int end = str.lastIndexOf("[\\img]");
        int start = str.lastIndexOf("[img]");
        if (start == -1 || end == -1 || start > end) System.out.println("null");
        else System.out.println(str.substring(start, end + 6));
    }
}

发表于 2019-01-18 16:55:32 回复(0)