我正在编写一个程序,我希望在两个字符串之间打印常用单词。好吧,我使用两个循环并在这两个循环中拆分这些字符串。但没有得到必要的结果。然后我改变了程序,然后我研究了外循环只运行一次。难道不能理解为什么?有人有什么想法吗?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str1[] = "Japan Korea Spain Germany Australia France ";
char str2[] = "England USA Russia Italy Australia India Nepal France";
char *tar1 = strtok(str1," ");
char *tar2 = NULL;
while(tar1)
{
tar2 = strtok(str2," ");
while(tar2)
{
if(strcmp(tar1,tar2)) printf("%s %s\n",tar1 , tar2);
tar2 = strtok(NULL," ");
}
tar1 = strtok(NULL," ");
tar2 = NULL;
}
return 0;
}
答案 0 :(得分:2)
您不能同时在两个不同的字符串上使用strtok
,并且您不能多次解析字符串,因为nul
已经通过使用#include <stdio.h>
#include <string.h>
#define MAXSTR 20
int main()
{
char str1[] = "Japan Korea Spain Germany Australia France ";
char str2[] = "England USA Russia Italy Australia India Nepal France";
char *tar1[MAXSTR];
char *tar2[MAXSTR];
char *tok;
int ind1 = 0, ind2 = 0;
int i, j;
tok = strtok(str1, " \t");
while(tok != NULL && ind1 < MAXSTR) {
tar1[ind1++] = tok;
tok = strtok(NULL, " \t");
}
tok = strtok(str2, " \t");
while(tok != NULL && ind2 < MAXSTR) {
tar2[ind2++] = tok;
tok = strtok(NULL, " \t");
}
for(i=0; i<ind1; i++) {
for(j=0; j<ind2; j++) {
if(strcmp(tar1[i], tar2[j]) == 0) {
printf("%s\n", tar1[i]);
break;
}
}
}
return 0;
}
打破字符串来修改字符串终止子。
此示例在检查匹配项之前,将令牌指针提取为每个输入字符串的指针数组。
Australia
France
节目输出:
<!DOCTYPE html>
<head>
<title>{{title}}</title>
<meta charset="{{charset}}">
<meta name="description" content="{{description}}">
<meta name="keywords" content="{{keywords}}">
<script type="text\javascript" src="some_kind_of_script_to_work_with_json_or_so.js">
</script>
</head>
<body>
<h1>{{H1}}</h1>
<div>{{some_kind_of_text}}</div>
<div>{{some_kind_of_text2}}</div>
</body>
</html>
答案 1 :(得分:1)
strtok()函数将字符串分解为零或更多的序列 非空的令牌。
换句话说:被
' '
替换为NUL(0)。
因此,您不能将strtok
两次使用相同的字符串。
正如@WeatherVane指出:你不能同时在两个不同的字符串上使用tar2 = strtok(str2," ");
。
代码的替代方法:
strtok
输出:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[] = "Japan Korea Spain Germany Australia France ";
char str2[] = "England USA Russia Italy Australia India Nepal France";
char *tar = strtok(str1, " ");
char *ptr;
size_t sz;
while (tar) {
if ((ptr = strstr(str2, tar)) != NULL) {
/* First string or starts with " " */
if ((ptr == str2) || (*(ptr -1) == ' ')) {
sz = strlen(tar);
/* Last string or ends with " " */
if ((*(ptr + sz) == ' ') || (*(ptr + sz) == '\0')) {
puts(tar);
}
}
}
tar = strtok(NULL, " ");
}
return 0;
}