首页 > 试题广场 >

表示数字

[编程题]表示数字
  • 热度指数:169348 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

将一个字符串中所有的整数前后加上符号“*”,其他字符保持不变。连续的数字视为一个整数。


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

输入描述:

输入一个字符串



输出描述:

字符中所有出现的数字前后加上符号“*”,其他字符保持不变

示例1

输入

Jkdi234klowe90a3

输出

Jkdi*234*klowe*90*a*3*
import re
while 1:
    try:
        print(re.sub('(\d+)', '*\g<1>*', input()))
    except:
        break

编辑于 2020-03-21 10:05:24 回复(6)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string a;
    while(getline(cin,a)){
  int len=a.size();
        for(int i=0;i<len;i++){
        if('0'<=a[i]&&a[i]<='9'){
                cout<<'*';
                while('0'<=a[i+1]&&a[i+1]<='9'){
                    cout<<a[i];
                    i++;
                }
                cout<<a[i]<<'*';
        }
            else
                cout<<a[i];
    }
        cout<<endl;
}return 0;
}
发表于 2016-08-25 16:32:42 回复(1)
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s;
    while(cin>>s){
        for(int i=0;i<s.length();i++){
            if(s[i]>='0'&&s[i]<='9'&&(i==0||s[i-1]<'0'||s[i-1]>'9')){
               s=s.substr(0,i)+"*"+s.substr(i);
			   i++;
			}
			if(s[i]>='0'&&s[i]<='9'&&(i+1==s.length()||s[i+1]<'0'||s[i+1]>'9')){
               s=s.substr(0,i+1)+"*"+s.substr(i+1);
			   i++;
			}
        }
        cout<<s<<endl;
    }
    return 0;
}

发表于 2016-08-17 19:48:39 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main(){
    string str;
    while(cin >> str){
        if(isdigit(str[0])) cout << '*';
        cout << str[0];
        int i = 1;
        while(i < str.size()){
            if(isdigit(str[i]) && !isdigit(str[i-1])) cout << '*';
            else if(!isdigit(str[i]) && isdigit(str[i-1])) cout << '*';
            cout << str[i++];
        }
        if(isdigit(str[str.size()-1])) cout << '*';
        cout << endl;
    }
    return 0;
}

发表于 2020-06-21 23:13:38 回复(1)
//思路:遇到数字后先输出'*',然后循环判断下一位字符,
//输出连续的所有数字后补'*',非数字则直接输出
#include<iostream>
#include<string>
using namespace std;
int main(){
    string s;
    while(getline(cin,s)){
        int len=s.size();
        for(int i=0;i<len;i++){
            if(s[i]>='0' && s[i]<='9'){
                cout<<'*';
                while(s[i+1]>='0' && s[i+1]<='9'){
                    cout<<s[i];
                    i++;
                }
                cout<<s[i]<<'*';
            }
            else
                cout<<s[i];
        }
        cout<<endl;
    }
    return 0;
}
发表于 2019-07-28 16:12:57 回复(1)
//我只想说这题就是一行代码的事而已!!!
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            String s = sc.nextLine();
            String ss = s.replaceAll("([\\d]+)","*$1*");
            System.out.println(ss);
        }
    }
}

发表于 2017-07-14 19:55:04 回复(2)
import java.util.Scanner;

public class Main{
     public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        while (in.hasNext()){
            String str = in.next();
            String res = "";
		   int pos = 0;
		   if(isNum(str,pos))
			   res+="*";
		   for(int i=0;i<str.length()-1;i++){
			   if((isNum(str,i) && !isNum(str,i+1))||(!isNum(str,i) && isNum(str,i+1))){
				   res+=String.valueOf(str.charAt(i))+"*";
			   }else{
				   res+=String.valueOf(str.charAt(i));
			   }
		   }
		   if(isNum(str,str.length()-1)){
			   res+=String.valueOf(str.charAt(str.length()-1))+"*";
		   }else{
			   res+=String.valueOf(str.charAt(str.length()-1));
		   }
		   System.out.println(res);
        }
        in.close();
     }
    public static boolean isNum(String str,int pos){
		   return (str.charAt(pos)>='0' && str.charAt(pos)<='9');
	   }
}


发表于 2017-07-10 10:53:16 回复(0)
s = input()
l = []  # 新建列表,依次加入并判断是否加星
if s[0].isdigit():
    l.append('*' + s[0])
else:
    l.append(s[0])  # 先判断第一位

for i in range(1,len(s)):
    if s[i - 1].isdigit() and not s[i].isdigit():  # 前数本非数,等于数尾加星
        l.append('*' + s[i])
    elif not s[i - 1].isdigit() and s[i].isdigit():  # 前非本数,等于数前加星
        l.append('*' + s[i])
    else:
        l.append(s[i])  # 前数本数不变,前非本非不变
if s[-1].isdigit():
    l.append('*')  # 尾数加星,尾非数不加
print(''.join(l))

发表于 2022-07-04 19:34:12 回复(0)
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String s = reader.readLine();
        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        //记录连续的整型
        int n = 0;
        for (int i = 0; i < chars.length; i++) {
            if (Character.isDigit(chars[i])) {
                if (n > 0) {
                    sb.append(chars[i]);
                }
                if (n == 0) {
                    sb.append("*").append(chars[i]);
                    n ++;
                }
                if (i == chars.length - 1) {
                    sb.append("*");
                }
            } else {
                if (n > 0) {
                    sb.append("*").append(chars[i]);
                    n = 0;
                } else {
                    sb.append(chars[i]);
                }
            }
        }
        System.out.println(sb.toString());
    }
}

发表于 2022-06-20 23:31:43 回复(0)
# str_in = input()

# # print(ord('1'))
# # print(ord('0')) # 48
# # print(ord('9')) # 57
# i_list = []
# for i in range(0,len(str_in)):
#     if 48<=ord(str_in[i])<=57:
#         i_list.append(i)
# print(i_list)
# left_list = []
# right_list = [] 
# all_list = []
# for i in i_list:
#     # 左不在,右边在,左边加*
#     if i-1 not in i_list and i+1 in i_list:
#         # str_out = str_in.replace(str_in[i], '*'+str_in[i])
#         left_list.append(i)
#     # 左在,右不在,右边加*
#     elif i-1 in i_list and i+1 not in i_list:
#         right_list.append(i)
#     # 都不在,两边加星
#     elif i-1  not in i_list and i+1 not in i_list:
#         all_list.append(i)
#     # 两边都不在,不加星
#     else:
#         pass
# # 问题是如果循环替换,则保存在i—list里面的下标会换

# # 思考,如果换一次在重新获得下标?
# # 那右怎么区分是否换了,避免出现**4*?

# 不用正则咋办啊啊啊啊
发表于 2022-04-18 12:58:45 回复(0)
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main(void)
{
    //定义两个字符数组,ch用于存放原数据,temp用于存放改变后的数据
    char ch[101],temp[121];
    gets(ch); //获取原数据
    int j = 0,i,t=0; //t用于记录连续的数字的个数
    for (i = 0; ch[i]!='\0'; i++) //遍历原数组
    {
        if (ch[i] >= '0' && ch[i] <= '9') //当遇到数字字符时
        {
        	t+=1; //t记录连续的数字个数,并加一
        	int flag=1; //记录该数字的左侧或右侧是否被改变
            //判断数字字符的左侧是否为非数字
            if (!isdigit(ch[i - 1]))
            {
                temp[j++] = '*';
                temp[j++] = ch[i];
                flag=0;//左侧被改变
            }
             //判断数字字符的右侧是否为非数字
            if (!isdigit(ch[i + 1]))
            {
                if(t==1) //连续部分只有一个数字时
                {
                	temp[j++]='*';
				}
				else {
					temp[j++]=ch[i];
					temp[j++]='*';
				}
				flag=0;//右侧被改变
            }
            if(flag) temp[j++]=ch[i]; //未被处理时
        }
        else {
		temp[j++] = ch[i]; //不是数字字符时
		t=0; //t归零,表示数字连续部分结束,下次重新计数
    }
}
     //在temp的最后一个有效字符后加上'\0',构成字符串,便于输出
    temp[j] = '\0';
    puts(temp);//输出结果
    return 0;
}
发表于 2022-04-08 11:07:41 回复(0)
代码应该没问题,但是用例:1**3和1a*b3无法通过,希望有大佬帮忙解答一下。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
    int mark = 0;
    char str[101] = {'\0'};
    while (~scanf("%s", str)) {
        int len = strlen(str);
        for (int i = 0; i < len; i++) {
            if (str[i] >= '0' && str[i] <= '9' && mark == 0) {
                printf("*");
                mark = 1;
            } else if ((str[i] < '0') || (str[i] > '9') && (mark == 1)) {
                printf("*");
                mark = 0;
            }
            printf("%c", str[i]);
            if (i == (len - 1) && str[i] >= '0' && str[i] <= '9') printf("*\n");
        }
    }
}

图一:

图二:

图三:

发表于 2022-04-01 23:18:12 回复(1)
跟‘\0’的比较太容易出错了~
#include<bits/stdc++.h>
using namespace std;

int main(){
    string s;
    while(cin>>s){
        const char *ch = s.c_str();
        string res = "";  //开辟另一个字符存结果
        while(*ch != '\0'){
            if(isdigit(*ch)){
                res += '*'; // 夹头
                while(isdigit(*ch)){  // 重复的快进
                    res += *ch;
                    ch++;
                }
                res += '*';  // 夹尾
            }
            if(*ch != '\0'){   // 更新
                res += *ch;
                ch++;
            }
        }
        cout<<res<<endl;
    }
}

发表于 2022-01-10 11:29:09 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = br.readLine()) != null) {
            StringBuilder sb = new StringBuilder();
            int len = s.length(), i = 0, j = 0;
            while (i < len) {
                while (i < len && !Character.isDigit(s.charAt(i))) {
                    sb.append(s.charAt(i++));
                }
                j = i;
                while (i < len && Character.isDigit(s.charAt(i))) {
                    i++;
                }
                if (i != j) {
                    sb.append("*").append(s, j, i).append("*");
                }
            }
            System.out.println(sb);
        }
    }
}

发表于 2021-09-22 09:59:05 回复(0)
一开始用比较麻烦的方法做的,脑子有蒙不转弯。后来一看其实counter那就结束了当再出现重置在前面再加个*就好了十几行的事-.-
不用正则大法的话,全转成list,当为数字在那一位insert(“*”),一旦counter重置在那一位再insert(“*”)就完事了。
以及。。正则大法好

#方法1:正则化
import re
while True:
    try:
        str1=input()
        str1=re.sub('(\d{1,})',r'*\1*',str1) #找到为数字的,长度一个或以上的,在满足的两侧添加*
        print(str1)
    except:
        break

#方法2: 非正则
while True:
    try:
        str1 = list(input())#读取数据
        counter = 0#用于判断是否数字开始或结束
        increaser = len(str1) #读取初始长度
        i=0
        while i <increaser:
            if str1[i].isdigit() != True and counter ==1:#当为数字结尾时(也就是字母起始位置添加)
                str1.insert(i, "*")
                counter = 0
                increaser=increaser+1#由于添加导致元素增加,遍历数+1
            elif str1[i].isdigit() == True and counter == 0:#当为数字起始时
                str1.insert(i, "*")
                counter= 1
                increaser=increaser+1
            i=i+1
        if str1[-1].isdigit() == True:#唯一情况全为数字,最后加上*就是了
            str1.append("*")
        print(''.join(str1))
    except:
        break

#方法3:记录自己脑抽
while True:
    try:
        str1 = input()#读取数据
        str2 = str1#转存数据
        index=[]
        counter = 0#用于判断数字的起始index
        for i in range (len(str2)):
            if str2[i].isdigit() != True:#当不是数字时替换成空格
                str2=str2.replace(str2[i], " ")
                counter=0#一旦出现字母则重设计数器,表示数字字符结束
            elif str2[i].isdigit() == True and counter == 0:#当计数器为0时记录当前index,也就是数字的初始index
                index.append(i)
                counter=counter+1#无视后续数字
        str2=str2.split()#以空格差分,提取出要改变的数字
        for i in range (len(str1)):#本来想用replace,但如果遇到*3*23*233这种顺序就会出错。
            if str1[i].isdigit() == True:#改为抹去str1里全部数字为空格
                str1=str1.replace(str1[i], " ")
        str1 = list(str1)#转换为list元素,由于空格填补,字母数字index不变,就可以用到前面得到的数字起始index
        for i in range (len(str2)):
            str3 = "*"+ str2[i]+"*"#把str1数字项的单个index逐个替换成 "*int*" 的形式
            str1[index[i]] = str3#由于其他项已被替换为空格,直接先根据起始数字index塞到一个元素里就行不管其他空格元素。
        str1=''.join(str1)#转换为string
        str1=str1.split()#删除多余空格元素
        str1=''.join(str1)#再变回string
        print(str1)#打印结果
    except:
        break



编辑于 2021-07-01 17:56:08 回复(0)
那些通过的人给出的代码都是错的,**能替换个毛线啊,被坑了,自己搞
我的思路:
1、首尾加上一个字符,这是为了应付单个字符的情况
2、判断相邻两个字符是否是数字到其他字符的过渡,是的话后面加上一个*,这里的两种情况用异或判断
比如f3s,f3是过渡,f后面加上*,3s是过渡,3后面加上*,遍历一遍就是f*3*s
while True:
    try:
        string = input()
        out = ''
        string = "a"+string+"a"
        for i in range(len(string)-1):
            if string[i].isdigit() ^ string[i+1].isdigit():
                out += string[i]+'*'
            else:
                out+=string[i]
        print(out[1:])
    except:
        break
发表于 2021-04-14 18:58:52 回复(0)
我的Java解决办法,这类题需要梳理逻辑,首先将字符串转变为字符数组chars,进行轮询遍历每一个字符,记录每一个字符为c
1.判断c是否为数字,如果是数字,有三种情况,是否是第一次出现的数字,1)是的话,要在数字前面加*,2)如果不是第一次出现的数字,就直接加c. 3)第三种情况是,如果数字在末尾,就直接自己加*,然后加入到字符串中
2.如果c不是数字,也分两种情况,1)字符前面有数字的,这种情况,是要加*的,然后加字符c  2)字符前面还是字符的,那就直接加字符c
逻辑明了以后,看代码
import java.util.Scanner;

/**
 * 表示数字
 * 将一个字符中所有出现的数字前后加上符号“*”,其他字符保持不变
 * * public static String MarkNum(String pInStr)
 * {
 * return null;
 * }
 * 注意:输入数据可能有多行
 * 输入描述:
 * 输入一个字符串
 * 输出描述:
 * 字符中所有出现的数字前后加上符号“*”,其他字符保持不变
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            System.out.println(markNum(s));
        }
    }

    public static String markNum(String s) {
        if (s == null || s.length() <= 0) {
            return "";
        }

        char[] chars = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        String numStr = "";
        boolean firstNum = true;
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (Character.isDigit(c)) {
                if (firstNum) {
                    numStr = "*" + c;
                    firstNum = false;
                } else {
                    numStr += c;
                }
                if (i == chars.length - 1) {
                    numStr += "*";
                    sb.append(numStr);
                }
            } else {
                if (!firstNum) {
                    numStr += "*";
                    sb.append(numStr);
                    sb.append(c);
                    numStr = "";
                    firstNum = true;
                } else {
                    sb.append(c);
                }
            }
        }
        return sb.toString();
    }
}
欢迎大家提出指正

发表于 2020-10-14 17:31:37 回复(1)
#include<iostream>
#include<cstring>
using namespace std;
bool judge(char s[],int i)
{
    bool r1=s[i]-'0'<10;
    bool r2=s[i-1]-'0'<10;
    if (r1 != r2)  //一个是数字字符,一个是字母字符
        return true;
    return false;
}
int main()
{
    char s[1000]="";
    while(scanf("%s",&s)!=EOF)
    {
        int len=strlen(s);
        if(s[0]-'0'<10) cout<<"*";  //特判第一个字符
        for (int i=1;i<len;i++)
        {
            if (judge(s,i)) cout<<s[i-1]<<"*";
            else cout<<s[i-1]; 
        }
        if(s[len-1]-'0'<10) cout<<s[len-1]<<"*";  //特判最后一个字符
        else cout<<s[len-1];
        cout<<endl;
    }
    return 0;
}

发表于 2020-08-17 10:34:27 回复(1)

#include<iostream>
#include<string>
using namespace std;
string FS(string s)
{
//总结(尽量不要用多重while循环,你不适合搞这个)
    string res;
    if(s.empty()) return res;
    //处理首部
    if(isdigit(s[0])) res=res+"*"+s[0];
    else if(!isdigit(s[0]))  res+=s[0];
    //处理中间,只考虑要不要在前面加"*",只有和前一位是两种类型才需要。
    for(int i=1;i<s.size();i++)
    {
     if(!isdigit(s[i])&&isdigit(s[i-1])) res=res+"*"+s[i];
     else if(isdigit(s[i])&&!isdigit(s[i-1])) res=res+"*"+s[i];
     else res+=s[i];
    }
    //考虑末尾一位。
    if(isdigit(s[s.size()-1])) res+="*";
    return res;
}
int main()
{
    string s;
    while(cin>>s)
    {
        string res=FS(s);
        cout<<res<<endl;
    }
    return 0;
}
看注释,参照了评论区一个大佬的修改了自己的代码,边界问题真烦人,有问题留言。
发表于 2020-07-22 11:36:45 回复(0)
观察*号的位置,分四种情况讨论:
#include<iostream>
(720)#include<string>
using namespace std;

int main(){
    string str;
    while(cin>>str){
        int leng = str.size();
        for(int i = 0;i < leng - 1;i++){
            //在数字和字母之间插入
           if((str[i] >= '0' && str[i] <= '9') && ((str[i + 1] >= 'a' && str[i + 1] <= 'z') || (str[i+1] >= 'A' && str[i + 1] <= 'Z'))){
               str.insert(i + 1,"*");
               leng++;
           }
            //在字母和数字之间插入
           if((str[i + 1] >= '0' && str[i + 1] <= '9') && ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))){
               str.insert(i + 1,"*");
               leng++;
           }
        }
        string temp = str;
        //头尾是数字的情况插入
        if(str[0] >= '0'&& str[0] <= '9'){
                temp = '*' + temp;
            }
        if(str[str.size() - 1] >= '0' && str[str.size() - 1] <= '9'){
                temp = temp + '*';
            }
        cout<<temp<<endl;
    }
    return 0;
}

发表于 2020-04-26 22:55:34 回复(0)

问题信息

难度:
572条回答 34725浏览

热门推荐

通过挑战的用户

查看代码