删除字符串中的字符的两种情况

版权声明:沉迷代码,难以自拔 https://blog.csdn.net/qq_33846054/article/details/50925749
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//删除一串字符中的特定字符(多个)
int main()
{
    char a[101],ch;
    int i,j,k;
    while (scanf ("%s %c",a,&ch)!=-1)
    {i=0;

        k=strlen(a);
        for (j=0;j<k;j++)//||while (a[j]!='\0')
        {
          if (a[j]!=ch)
          {
              a[i]=a[j];
              i++;
          }
        }
        a[i]='\0';
        printf ("%s",a);
    }
    //后浪J一直循环,当后浪不等于特定字符时说明可以推前浪了。
    //勿忘封底!
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//删除一串字符(<=100)中的某个特定字符(1个)
int main()
{
    char a[101],ch;
    int i,k,t;
    while (scanf ("%s %c",a,&ch)!=-1)
    {
        k=strlen (a);
        for (i=0;i<k;i++)
        {
            if (a[i]==ch)
            {
                t=i;
                break;
            }
        }
        for (i=t;i<=k;i++)
        {
            a[i]=a[i+1];
        }//或者封边:a[i]='\0'
        printf ("%s ",a);
    }
    return 0;
}

具体问题:

1. 字符串定位
有一个不含空格的字符串(长度小于100),要统计其中有多少个*,并输出该字符串去掉*后的新字符串。 林大OJ  (903题)
Input 输入数据有多组,每组1个连续的字符串;
Output  在1行内输出该串内有多少个* 和去掉*后的新串。
Example Input:
Goodggod223**df2*w
Qqqq*
Example output:
3 Goodggod223df2w
1 Qqqq


#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
char a[101];
int i,j,k,count;
while (scanf ("%s",a)!=-1)
{
    getchar();//输完scanf的时候打了空格,在下一次输入的时候第一个字符会自动取空格必须用getchar吸收掉
    count=0;
    k=strlen(a);//不能用k--不然K值改变,影响下面的循环
    i=0;
    while (a[i]!='\0')
    {
        if (a[i]=='*')
        {
            count++;

        }
        i++;
    }
    j=0;//J必须清零!!!!勿忘!
    for (i=0;i<k;i++)
    {
        if (a[i]!='*')
        {
            a[j]=a[i];
            j++;
        }

    }
    a[j]='\0';
    printf ("%d %s\n",count,a);//如果不加\n那么就必须人工输入回车!!就会造成误差!两组数据间\n不能丢!

}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33846054/article/details/50925749