【问题标题】:How to get a specific character in a string如何获取字符串中的特定字符
【发布时间】:2015-04-05 18:09:41
【问题描述】:

我有一个字符串(一个方程或多项式),我想得到字符串中的一个特定字符。例如,如果用户输入:

4x^2+3x-9

我想为每个术语创建一个节点,所以在第一个节点中,我需要在其因子中存储“4”,在其幂中存储“2”。以下是我识别节点的代码。

typedef struct node *ptr;
struct node
{
char sign;
int power;
int factor;
ptr next;
};
typedef ptr poly;
typedef ptr position;

以下是我已经为接受用户的多项式而编写的代码:

void fillPoly(poly polynomial)
{
system("cls");
char polyn[100];
printf("\t\t\tEnter your polynomial please. Your polynomial should not exceed 7 terms.\n\t\t\t");
scanf("\t\t\t%s",polyn);
position temp;
temp=polynomial;
while (polyn!='\0')
{
    (temp)->next=(position)malloc(sizeof (struct node));
 // Here is the problem

}     
}

分配完节点后不知道怎么继续,怎么取因子和幂来填充?

【问题讨论】:

  • 两个问题:第一个是你读取用户的输入两次,一次是scanf,另一次是gets,第二个输入覆盖了字符数组。第二个问题是要转义字符串或字符文字中的特殊字符,您应该使用 back 斜杠,例如'\0'.
  • @JoachimPileborg 我已经编辑过了,现在正确吗?但是,我正在寻找的是一种分别获取因子和幂并将它们存储在每个术语的节点中的方法。我的问题清楚了吗?

标签: c data-structures linked-list


【解决方案1】:

这段代码 sn-p 会帮助你。

for(int i=0;i<strlen(poly);i++) {   
// You need only to fetch 4 data members from the string    
// 1 - Sign    
    temp->sign = poly[i++];   
// 2 - Factor    
    temp->factor = poly[i++] - '0' ; // to convert char to int    
// 3 - x ( is ignored in ur case  )    
// 4 - Power
     temp->power =  poly[i++] - '0' ;

 }

输入应以符号开头,否则将导致错误答案。这只是一个基本代码。应根据您提供的输入类型进行进一步修改。我希望你能做到。

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    相关资源
    最近更新 更多