字符串操作练习以及scanf()的注意事项

/*
 ============================================================================
 Name        : String.c
 Author      : lf
 Version     :
 Copyright   : Your copyright notice
 Description : 字符串操作练习以及scanf()的注意事项
 1 字符串的插入
 2 删除字符串中的字符
 3 scanf()的注意事项
 ============================================================================
 */

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

void test1();
void test2();
void test3();

int main(void) {
	test1();
	test2();
	test3();
	return EXIT_SUCCESS;
}


/**
 * 字符串的插入
 * 操作步骤:
 * 1 找到插入的位置
 * 2 保存插入位置之后的字符串
 * 3 将插入位置之后的字符串截掉
 * 4 原字符串与待插入字符串组拼
 * 5 原字符串与原插入位置后的字符串组拼
 */
void test1(){
	char insertString[10]=" hello vc";
	char oldString[40]="hello java hello C++ hello c";
	printf("oldString=%s\n",oldString);
	char searchString[10]="C++";
	char *p=strstr(oldString,searchString);
	if (p!=NULL) {
		char tempString[20];
		strcpy(tempString,p+strlen(searchString));
		printf("tempString=%s\n",tempString);
		*(p+strlen(searchString))='\0';
		printf("oldString=%s\n",oldString);
		strcat(oldString,insertString);
		printf("oldString=%s\n",oldString);
		strcat(oldString,tempString);
		printf("oldString=%s\n",oldString);
	} else {
		printf("NOT FOUND\n");
	}
	printf("============\n");
}


/**
 * 删除字符串中的字符
 */
void test2() {
	int location = 0;
	char oldString[40] = "hello java hello C++ hello c";
	printf("oldString=%s\n", oldString);
	char newString[40];
	char deleteChar = 'l';
	char *p = oldString;
	while (*p != '\0') {
		if (*p != deleteChar) {
			newString[location] = *p;
			location++;
		} else {

		}
		p++;
	}
	printf("newString=%s\n", newString);
	strcpy(oldString,newString);
	printf("oldString=%s\n", oldString);
	printf("============\n");
}

/**
 *  scanf()的注意事项
 *  scanf()会将空格,制表符,空格,换行符,换页符当做数据的终止符.
 *  但是gets()不会,所以在输入字符串含有以上字符时可gets()
 */
void test3() {
//	char a[30];
//	scanf("%s", a);
//	printf("a=%s\n", a);

	char b[30];
	gets(b);
	printf("b=%s\n", b);
}



你可能感兴趣的:(字符串,C语言)