将字符串的字符存储在变量C中

时间:2018-06-22 09:39:11

标签: c string

我有一个字符串

 private void button2_Click(object sender, EventArgs e)
 {
     string directory = AppDomain.CurrentDomain.BaseDirectory + "output.txt";
     using (SaveFileDialog dialog = new SaveFileDialog())
     {
         dialog.Filter = "txt files (*.txt);
         dialog.FilterIndex = 2;
         dialog.RestoreDirectory = true;

         if (dialog.ShowDialog() == DialogResult.OK)
         {
             File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
         }
     }
} 

我想创建一个新字符串,它是str = "hello" “ he”的前两位。

我该如何在C语言中做到这一点?

1 个答案:

答案 0 :(得分:1)

使用strncpy(),如下所示:

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

int main(void) {
    char src[] = "hello";
    char dest[3]; // Two characters plus the null terminator

    strncpy(dest, &src[0], 2); // Copy two chars, starting from first character
    dest[2] = '\0';

    printf("%s\n", dest);
    return 0;
}

输出: