C/C++ 字符串拷貝處理


C語言的字符串操作

strtok 實現字符串切割: 將字符串根據分隔符進行切割分片.

#include <stdio.h>

int main(int argc, char* argv[])
{
	char str[] = "hello,lyshark,welcome";
	char *ptr;

	ptr = strtok(str, ",");
	while (ptr != NULL)
	{
		printf("切割元素: %s\n", ptr);
		ptr = strtok(NULL, ",");
	}
	system("pause");
	return 0;
}

strlen 獲取字符串長度

#include <stdio.h>

int main(int argc, char* argv[])
{
	char Array[] = "\0hello\nlyshark";
	char Str[] = { 'h', 'e', 'l', 'l', 'o' };

	int array_len = strlen(Array);
	printf("字符串的有效長度:%d\n", array_len);
	int str_len = strlen(Str);
	printf("字符串數組有效長度: %d\n", str_len);
	
	int index = 0;
	while (Str[index] != '\0')
	{
		index++;
		printf("Str數組元素: %c --> 計數: %d \n", Str[index], index);
	}

	system("pause");
	return 0;
}

strcpy 字符串拷貝:

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

int main(int argc, char* argv[])
{
	char Array[] = "hello lyshark";
	char tmp[100];

	// 學習strcpy函數的使用方式
	if (strcpy(tmp, Array) == NULL)
		printf("從Array拷貝到tmp失敗\n");
	else
		printf("拷貝后打印: %s\n", tmp);

	// 清空tmp數組的兩種方式
	for (unsigned int x = 0; x < strlen(tmp); x++)
		tmp[x] = ' ';

	memset(tmp, 0, sizeof(tmp));
	
	// 學習strncpy函數的使用方式
	if (strncpy(tmp, Array, 3) == NULL)
		printf("從Array拷貝3個字符到tmp失敗\n");
	else
		printf("拷貝后打印: %s\n", tmp);

	system("pause");
	return 0;
}

strcat字符串連接: 將由src指向的空終止字節串的副本追加到由dest指向的以空字節終止的字節串的末尾

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

int main(int argc, char* argv[])
{
	char str1[50] = "hello ";
	char str2[50] = "lyshark!";

	char * str = strcat(str1, str2);
	printf("字符串連接: %s \n", str);

	str = strcat(str1, " world");
	printf("字符串連接: %s \n", str);

	str = strncat(str1, str2, 3);
	printf("字符串連接: %s \n", str);

	system("pause");
	return 0;
}

strcmp 字符串對比:

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

int Str_Cmp(const char * lhs, const char * rhs)
{
	int ret = strcmp(lhs, rhs);
	if (ret == 0)
		return 1;
	else
		return 0;
}

int main(int argc, char* argv[])
{
	char *str1 = "hello lyshark";
	char *str2 = "hello lyshark";

	int ret = Str_Cmp(str1, str2);
	printf("字符串是否相等: %d \n", ret);

	if (!strncmp(str1, str2, 3))
		printf("兩個字符串,前三位相等");

	system("pause");
	return 0;
}

strshr 字符串截取:

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

int main(int argc, char* argv[])
{
	const char str[] = "hello ! lyshark";
	char *ret;

	ret = strchr(str, '!');
	printf("%s \n", ret);

	system("pause");
	return 0;
}

字符串逆序排列:

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

void Swap_Str(char *Array)
{
	int len = strlen(Array);
	char *p1 = Array;
	char *p2 = &Array[len - 1];
	while (p1 < p2)
	{
		char tmp = *p1;
		*p1 = *p2;
		*p2 = tmp;
		p1++, p2--;
	}
}

int main(int argc, char* argv[])
{
	char str[20] = "hello lyshark";
	Swap_Str(str);
	
	for (int x = 0; x < strlen(str); x++)
		printf("%c", str[x]);

	system("pause");
	return 0;
}

實現字符串拷貝:

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

// 使用數組實現字符串拷貝
void CopyString(char *dest,const char *source)
{
	int len = strlen(source);
	for (int x = 0; x < len; x++)
	{
		dest[x] = source[x];
	}
	dest[len] = '\0';
}

// 使用指針的方式實現拷貝
void CopyStringPtr(char *dest, const char *source)
{
	while (*source != '\0')
	{
		*dest = *source;
		++dest, ++source;
	}
	*dest = '\0';
}
// 簡易版字符串拷貝
void CopyStringPtrBase(char *dest, const char *source)
{
	while (*dest++ = *source++);
}

int main(int argc, char* argv[])
{
	char * str = "hello lyshark";
	char buf[1024] = { 0 };
	CopyStringPtrBase(buf, str);
	printf("%s \n", buf);

	system("pause");
	return 0;
}

格式化字符串:

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

int main(int argc, char* argv[])
{
	// 格式化填充輸出
	char buf[30] = { 0 };
	sprintf(buf, "hello %s %s", "lyshark","you are good");
	printf("格式化后: %s \n", buf);

	// 拼接字符串
	char *s1 = "hello";
	char *s2 = "lyshark";
	memset(buf, 0, 30);
	sprintf(buf, "%s --> %s", s1, s2);
	printf("格式化后: %s \n", buf);

	// 數字裝換位字符串
	int number = 100;
	memset(buf, 0, 30);
	sprintf(buf, "%d", number);
	printf("格式化后: %s \n", buf);

	system("pause");
	return 0;
}

動態存儲字符串:

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

int main(int argc, char* argv[])
{
	// 分配空間
	char **p = malloc(sizeof(char *)* 5);
	for (int x = 0; x < 5;++x)
	{
		p[x] = malloc(64); 
		memset(p[x], 0, 64);
		sprintf(p[x], "Name %d", x + 1);
	}

	// 打印字符串
	for (int x = 0; x < 5; x++)
		printf("%s \n", p[x]);

	// 釋放空間
	for (int x = 0; x < 5; x++)
	{
		if (p[x] != NULL)
			free(p[x]);
	}

	system("pause");
	return 0;
}

字符串拼接:

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

char * StringSplicing(char *String1, char  *String2)
{
	char Buffer[1024];

	int index = 0;
	int len = strlen(String1);
	while (String1[index] != '\0')
	{
		Buffer[index] = String1[index];
		index++;
	}
	while (String2[index - len] != '\0')
	{
		Buffer[index] = String2[index - len];
		index++;
	}
	Buffer[index] = '\0';

	char *ret = (char*)calloc(1024, sizeof(char*));
	if (ret)
		strcpy(ret, Buffer);
	return ret;
}

int main(int argc, char* argv[])
{
	char *str1 = "hello ";
	char *str2 = "lyshark ! \n";

	char * new_str = StringSplicing(str1, str2);
	printf("拼接好的字符串是: %s", new_str);

	system("pause");
	return 0;
}

實現strchr:

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

char * MyStrchr(const char *String, char ch)
{
	char *ptr = String;
	while (*ptr != '\0')
	{
		if (*ptr == ch)
			return ptr;
		ptr++;
	}
	return NULL;
}

int main(int argc, char* argv[])
{
	char Str[] = "hello lyshark";
	char ch = 's';

	char *ptr = MyStrchr(Str, ch);
	printf("輸出結果: %s \n", ptr);

	system("pause");
	return 0;
}

自己實現尋找字符串子串:

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

// 查找子串第一次出現的位置
char *MyStrStr(const char* str, const char* substr)
{
	const char *mystr = str;
	const char *mysub = substr;

	while (*mystr != '\0')
	{
		if (*mystr != *mysub)
		{
			++mystr;
			continue;
		}

		char *tmp_mystr = mystr;
		char *tmp_mysub = mysub;

		while (tmp_mysub != '\0')
		{
			if (*tmp_mystr != *tmp_mysub)
			{
				++mystr;
				break;
			}
			 ++tmp_mysub;
		}


		if (*tmp_mysub == '\0')
		{
			return mystr;
		}
	}
	return NULL;
}

int main(int argc, char* argv[])
{

	char *str = "abcdefg";
	char *sub = "fg";

	char * aaa = MyStrStr(str, sub);

	printf("%s", aaa);

	system("pause");
	return 0;
}

刪除字符串中連續字符

#include <stdio.h>
char del(char s[],int pos,int len)   //自定義刪除函數,這里采用覆蓋方法
 {
   int i;
   for (i=pos+len-1; s[i]!='\0'; i++,pos++)
     s[pos-1]=s[i];   //用刪除部分后的字符依次從刪除部分開始覆蓋
   s[pos-1]='\0';
   return s;
 }
int main(int argc, char *argv[])
{
  char str[50];
  int position,length;
  printf ("please input string:\n");
  gets(str);   //使用gets函數獲得字符串
  printf ("please input delete position:");
  scanf("%d",&position);
  printf ("please input delete length:");
  scanf("%d",&length);
  del(str,position,length);
  printf ("the final string:%s\n",str);
  return 0;
}

C++的字符串操作

在C語言中想要輸出數據需要使用Printf來實現,但C++中引入了另一種輸出方式,C++中形象的將此過程稱為流,數據的輸入輸出是指由若干個字節組成的字節序列,這些序列從一個對象中傳遞到另一個對象,我們將此過程形象的表示為數據的流,數據流可以包括ASCII字符,二進制數據,圖形圖像數據,音頻數據等,流都將可以操作.

字符串類的初始化

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
	string str("hello lyshark"); // 定義一個字符串

	string str_1(str);           // 構造函數,將 str中的內容全部復制到str_1
	cout << str_1 << endl;
	string str_2(str, 2, 5);     // 構造函數,從字符串str的第2個元素開始,復制5個元素,賦值給str_2
	cout << str_2 << endl;
	string str_3(str.begin(), str.end()); // 復制字符串 str 的所有元素,並賦值給 str_3
	cout << str_3 << endl;

	char ch[] = "lyshark";
	string str_4(ch, 3);    // 將字符串ch的前5個元素賦值給str_4
	cout << str_4 << endl;

	string str_5(5, 'x');   // 將 5 個 'X' 組成的字符串 "XXXXX" 賦值給 str_5
	cout << str_5 << endl;
	
	system("pause");
	return 0;
}

標准輸出流: 首先我們演示標准的輸入輸出,其需要引入頭文件<iostream>

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
	char str[] = "lyshark";
	int number = 0;

	cout << "hello: " << str << endl;
	cin >> number;
	if (number == 0)
	{
		cerr << "Error msg" << endl;  // 標准的錯誤流
		clog << "Error log" << endl;  // 標准的日志流
	}

	int x, y;
	cin >> x >> y;                      // 一次可以接受兩個參數
	freopen("./test.log", "w", stdout); // 將標准輸出重定向到文件

	system("pause");
	return 0;
}

格式化輸出: 在程序中一般用cout和插入運算符“<<”實現輸出,cout流在內存中有相應的緩沖區。

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
	cout << hex << 100 << endl;             // 十六進制輸出
	cout << dec << 100 << endl;             // 十進制輸出
	cout << oct << 100 << endl;             // 八進制輸出
	cout << fixed << 10.053 << endl;        // 單浮點數輸出
	cout << scientific << 10.053 << endl;   // 科學計數法

	cout << setw(10) << "hello" << setw(10) << "lyshark" << endl;  // 默認兩個單詞之間空格

	cout << setfill('-') << setw(10) << "hello" << endl; // 指定域寬,輸出字符串,空白處以'-'填充

	for (int x = 0; x < 3; x++)
	{
		cout << setw(10) << left << "hello" ; // 自動(left/right)對齊,不足補空格
	}

	cout << endl;
	system("pause");
	return 0;
}

單個字符輸出: 流對象中,提供了專用於輸出單個字符的成員函數put

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
	char *str = "lyshark";

	for (int x = 6; x >= 0; x--)
		cout.put(*(str + x));  // 每次輸出一個字符
	cout.put('\n');

	system("pause");
	return 0;
}

標准輸入流: 通過測試cin的真值,判斷流對象是否處於正常狀態.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
	float grade;

	while (cin >> grade)
	{
		if (grade >= 85)
			cout << grade << " good" << endl;
	}
	system("pause");
	return 0;
}

讀取字符串: getline函數的作用是從輸入流中讀取一行字符

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char* argv[])
{
	char str[20];
	int x, y, z;

	cin >> x >> y >> z;
	cout << x << y << z;

	cin.getline(str, 20);        // 讀入字符遇到\n結束讀取
	cout << str << endl;

	cin.getline(str, 20, 'z');  // 讀入字符遇到z字符才結束
	cout << str << endl;

	system("pause");
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM