C中的字符串操作

时间:2010-12-29 08:18:02

标签: c string

例如,我有一个字符串<abc="xyz">

abc可以改变,xyz也是如此。我需要一种方法来找出两个双引号之间的值。我怎么用C做到这一点? 我可以使用任何标准的lib函数吗?没有明确的指针跳舞?

3 个答案:

答案 0 :(得分:2)

你必须浏览字符串。

你需要的一切都在那里: http://www.cppreference.com/stdstring/index.html

答案 1 :(得分:1)

如果表单总是将成为<abc="xyz"> ,您知道字符串不会超过特定长度,那么以下内容将非常有效好:

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

int getNameAndValue(char *str, 
                    char *name, 
                    size_t nameLen, 
                    char *value, 
                    size_t valueLen)
{
  char *delimiters="<>=\"";
  char *token;
  int result = 0;

  /**
   * Make a local working copy of the input string, since strtok needs to
   * be able to write to it. 
   */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
  /**
   * If we know we're working in C99, use a variable length array for the 
   * local copy
   */
  char strCopy[strlen(str) + 1]; 
#else
  /**
   * If we *don't* know we're working in C99, use malloc() to create
   * the local copy
   */
  char *strCopy = malloc(strlen(str) + 1);
#endif

  strcpy(strCopy, str);
  token = strtok(strCopy, delimiters);
  if (!token)
    result = 0;
  else
  {
    strncpy(name, token, nameLen);
    name[nameLen-1] = 0;              // make sure string is 0-terminated, since
  }                                   // strncpy doesn't guarantee it

  token = strtok(NULL, delimiters);
  if (!token)
    result = 0;
  else
  {
    strncpy(value, token, valueLen);
    value[valueLen-1] = 0;
    result = 1;
  }

#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
  /**
   * Make sure we release the local copy for the C89 version; 
   * the C99 version will destroy the VLA automatically at
   * function exit.
   */
  free(strCopy);
#endif

  return 1;
}

int main(void)
{
  char *source = "<abc=\"xyz\">";
  char name[5], value[5];

  if (getNameAndValue(source, name, sizeof name, value, sizeof value))
    printf("name = %s, value = %s\n", name, value);

  return 0;
}

对于任何更复杂的东西,请使用像expat这样的xml解析库。

答案 2 :(得分:0)

int main()
{
    char const* s = "<abc=\"xyz\">";
    char a[4], b[4];

    int scanned = sscanf (s, "<%3[^=]%*[^\"]\"%3[^\"]", a, b);
    printf("scanned = %i\n", scanned);

    printf("%s\n", a); // prints abc
    printf("%s\n", b); // prints xyz
}

编辑添加了对子字符串长度的检查。