【问题标题】:String manipulation with escape keys使用转义键操作字符串
【发布时间】:2014-07-23 15:21:44
【问题描述】:

我正在尝试找出一种将给定字符串操作为特殊字符的方法。

例如 - 给出的字符串:"\\n"

我想得到:

// manipulations should take place here

"\n"

有什么“聪明”的方法吗?

干杯。

【问题讨论】:

  • 只是一个变量... 生病编辑它,以便更清楚我想要什么(有点难以解释)

标签: c string char escaping


【解决方案1】:
    int i, j = 0;
    for(i = 0; i < strlen(str); i++){

           if(str[i] == '\\' && str[i+1] == '\\')
                     i++;

           str[j] = str[i];
           j++;

    }
    str[j] = '\0';

【讨论】:

  • 你能解释一下为什么吗?你想看“\n”还是想看一个新行(即空白)。
【解决方案2】:
#include <stdio.h>

int main (void) {
    char str[] = "test text.\\n";
    char *s, *d;

    printf("%s\n", str);

    d = s = str;
    while(*s){
        if(*s == '\\' && s[1] == 'n'){
            *d++ = '\n';
            s += 2;
        } else {
            *d++ = *s++;
        }
    }
    *d = '\0';
    printf("<%s>", str);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2017-06-07
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多