c - 将 char* 中的字符替换为 double 值

标签 c string

我有一个 char *,我需要将一个字符替换为 double 值(未知位数)。所以我认为我需要计算位数,然后创建一个 realloc() 并替换字符。我只是不确定如何计算位数并进行此替换

例如:

char *c = strdup("a+b");
double d = 10;
//I'd like to replace 'a' for 10.  
//then 'c' would be : 10+b. 
//Next iteration I need to change the 'b' value then I get:
//c = 10 + 3

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char **argv)
{
  const char* s = "a+b";
  double d = 10.23142;

  //determine the string length needed for printing d
  size_t n = snprintf(NULL, 0, "%g", d);
  // old string length + n - 1 for replaced b +  1 for '\0'        
  char* new_s = malloc( strlen(s) + n - 1 + 1); 

  //write the double
  sprintf(new_s, "%g", d);  

  //skip the first byte (where b is) at the source and the double's length at the destination
  strcpy(new_s + n, s + 1);     

  printf("%s\n", new_s); //prints 10.2314+b 

  free(new_s);
  return 0;
}

在这种指针算术中很容易出现差一错误,因此像 gcc 的 mudflap 或 AddressSanitizer 这样的东西对于检查以确保程序不会在某些地方进入未定义的行为非常有用。

如果可以的话,最好使用 C++,这样您就不必担心此类问题:

#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
  string s = "a+b";
  double d = 10.23142;

  s.replace(0,1,to_string(d));
  cout<<s<<endl;

  return EXIT_SUCCESS;
}

关于c - 将 char* 中的字符替换为 double 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363099/

相关文章:

string - Go 编译器是否连接由加号分隔的字符串?

c - 如何用C语言使用二进制推送通知格式?

c - 如何在C编程中将IP地址定义为常量变量?

C 宏仅更改函数调用而不更改函数定义

c - 为什么我的 for 循环不在第二个循环中打印?

python - 为什么这个字符串比较返回 False?

c - 我正在尝试将多个客户端连接到该服务器,但代码似乎不起作用>

c++ - 如何同时应用多种格式化方法,例如 ."1,234,567,890"和 "12-3456-7890"到 "1,2-34,56-7,890"

python - 带有转义字符的 json.loads

string - 默认情况下 Erlang 二进制字符串