c 包含字符串 demo
时间: 2023-10-17 21:04:23 浏览: 14
以下是一个简单的 C 代码示例,演示了如何使用字符串:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello";
char str2[50] = "World";
char str3[50];
// 将 str1 复制到 str3 中
strcpy(str3, str1);
printf("strcpy(str3, str1): %s\n", str3);
// 将 str1 和 str2 连接到 str3 中
strcat(str3, str2);
printf("strcat(str3, str2): %s\n", str3);
// 返回 str1 的长度
printf("strlen(str1): %d\n", strlen(str1));
return 0;
}
```
输出结果为:
```
strcpy(str3, str1): Hello
strcat(str3, str2): HelloWorld
strlen(str1): 5
```
相关问题
getcommandline c语言使用demo
以下是一个简单的使用 C 语言获取命令行参数的示例代码:
```c
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %d\n", argc);
for(int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
```
在这个示例中,`argc` 表示命令行参数的数量,`argv` 是一个字符串数组,包含了所有的命令行参数。在 `for` 循环中,我们遍历这个数组并打印出每个参数。
例如,如果你在命令行输入 `./demo hello world`,那么输出将会是:
```
Number of arguments: 3
Argument 0: ./demo
Argument 1: hello
Argument 2: world
```
dbus c语言 demo
下面是一个简单的DBus C语言示例,它创建了一个DBus连接,发送一个DBus消息,等待并接收回复消息:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dbus/dbus.h>
int main(int argc,char **argv){
DBusError err;
DBusConnection *conn;
DBusMessage *msg,*reply;
int ret;
// 初始化错误变量
dbus_error_init(&err);
// 连接到DBus session bus
conn = dbus_bus_get(DBUS_BUS_SESSION,&err);
if(dbus_error_is_set(&err)){
fprintf(stderr,"Connection Error (%s)\n",err.message);
dbus_error_free(&err);
return EXIT_FAILURE;
}
// 创建DBus消息
msg = dbus_message_new_method_call("org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"ListNames");
if(!msg){
fprintf(stderr,"Message Null");
return EXIT_FAILURE;
}
// 发送DBus消息并等待回复
reply = dbus_connection_send_with_reply_and_block(conn,msg,-1,&err);
dbus_message_unref(msg);
if(!reply){
fprintf(stderr,"Reply Null (%s)\n",err.message);
dbus_error_free(&err);
return EXIT_FAILURE;
}
// 打印回复消息中的字符串
if(dbus_message_get_args(reply,&err,DBUS_TYPE_ARRAY,
DBUS_TYPE_STRING,&ret,DBUS_TYPE_INVALID)){
printf("List of services:\n");
for(int i=0;i<ret;i++){
char *s;
dbus_message_iter_get_basic(&ret,&s);
printf("%s\n",s);
dbus_message_iter_next(&ret);
}
}
// 释放DBus连接和消息
dbus_message_unref(reply);
dbus_connection_close(conn);
return EXIT_SUCCESS;
}
```
这个例子连接到DBus的会话总线,发送一个`ListNames`请求,等待回复并打印回复中包含的服务列表。需要注意的是,如果没有连接到总线或发送消息出错,代码会返回EXIT_FAILURE,否则返回EXIT_SUCCESS。