c - 仅从字符串中获取前 2 个字符

标签 c string

我想用不同字符串的前两个字符组成一个字符串

所以我有:

int main(int argc, string argv[])
{
    string s = argv[1];
    string key = // here is where I dont know how to get the first 2 chars.
    printf("%s\n", key);
} 

如果argv[1]是:1220kjs,我需要字符串“key”为12,argv[1]可以是数字或字符。因此,如果 argv[1] 输入为 jths528as,我需要字符串“key”为“jt”。

我尝试了各种方法,但无法编译。 s.Substring(0,2) 给我错误:成员引用基类型 'string' aka 'char *') 不是结构或 union

我找到了一个解决方案:

string t = argv[1];
char key[3];
strncpy(key, t, 2);
key[2] = '\0';

最佳答案

鉴于您在问题中提供的内容以及对您的意思的解释,我只能假设 argv 是 int 或 char 的二维数组。

string a = argv[1][0]; // so this has 1
string b = argv[1][1]; // this has 2 in it

你希望 c 为 12。

    int[,] t = new int[2, 6] {{1,2,3,4,5,6},
                              {1,2,2,0,8,5}};

    string a = Convert.ToString(t[1,0]);
    string b = Convert.ToString(t[1,1]);

    string c = a+b; // "12"

如果需要,您可以从此处将其转换为数字 12。

关于c - 仅从字符串中获取前 2 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889788/

相关文章:

C、for循环: unexplained change of the index value from 0 to the end condition number

c - 如何在障碍处正确同步线程

objective-c - objective-c - 导入 .m 和 .h 文件 - 它有什么作用

Javascript 字符串替换怪异 -- $$$$ 折叠为 $$ -- 这个结果背后的原因是什么?

xcode - 如何在 Swift 中实现 ROT13 函数?

c++ - 为什么 C++ 标准库与编译器而不是操作系统捆绑在一起?

c - 程序无法到达代码的特定部分

html - Xcode Swift 2 HTML img src

r - R 中的这个正则表达式模式有什么问题?

Java 无法将枚举用作注释的字符串参数(例如 : Jackson)